javascript - JSON Array Not Parsing As Expected -
i have data structured follows..
[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}],[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}]
i retrieve data data tag with
var formdata = $(document.getelementbyid('form-render-data')).data('form');
i cannot iterate on each array , access each object inside it. have tried parsing , stringifying surrounding [] makes no difference.
looping through using index prints each character in string. not stringifying before being put in data tag either.
update: there has been confusion on have been trying achieve try best explain full process.
forms being built using formbuilder.io. exporting json data forms , storing them in mysql db using sails js framework. however, there possibility of multiple forms being made 1 session, hence need multiple arrays. i'm returning json in request without stringifying or parsing.
i have tried wrapping json in square brackets i'm still not having luck.
your code works if fix json
var formdata = $('#form-render-data').data('form'); console.log(formdata)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="form-render-data" data-form='[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}, {"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}]'>data</div>
if not, cannot parse .data, need attr("data-form") , split
var formdata = $('#form-render-data').attr('data-form'); console.log(json.parse(formdata.split('],[').join(",")))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="form-render-data" data-form='[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}],[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}]'>data</div>
or wrap
var formdata = $('#form-render-data').attr('data-form'); console.log(json.parse("["+formdata+"]"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="form-render-data" data-form='[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}],[{"type" : "text", "label" : "some label"},{"type" : "other type", "label": "other label"}]'>data</div>
Comments
Post a Comment