Rishi Rishi - 23 days ago 9
jQuery Question

JSON parsing issue from the hidden text field

I have following JSON string saved in the input hidden field,

[{"pro":{"draft":{"create":"1"},"submitted":{"edit":"1","delete":"0"}},"ind":{"draft":{"create":""},"submitted":{"edit":"","delete":""}}}]


When I am trying to retrieve JSON from the hidden text field like,

JSON.stringify($('#SecurityJSON').val()) //returns "[{"


But if try directly passing field contents into JSON stringify then it returns proper JSON,

JSON.stringify([{"pro":{"draft":{"create":"1"},"submitted":{"edit":"1","delete":"0"}},"ind":{"draft":{"create":""},"submitted":{"edit":"","delete":""}}}]) //works well


Do I need to parse/format text field to retrieve correct JSON ?

Answer

How about this solution. Hope it helps!

var data = {}
data = $.parseJSON($('#SecurityJSON').val());
console.log(data[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="hidden" value='[{"pro":{"draft":{"create":"1"},"submitted":{"edit":"1","delete":"0"}},"ind":{"draft":{"create":""},"submitted":{"edit":"","delete":""}}}]'
    id="SecurityJSON">