I am new to JavaScript. I have done similar requirements in Java using org.json library.
I have a String:
var string = "{\"id\" :[\"\"],\"State\" :[\"TX\",\"IA\"]}";
I am converting that string to a JSONObject using this:
var obj = JSON.parse(string);
I am trying to achieve this using JavaScript or jQuery. How do i get the JSONArrays inside this JSONObject. Please help me. Thanks in advance.
3 Answers 3
var jsonStr = "{\"id\" :[\"\"],\"State\" :[\"TX\",\"IA\"]}";
var jsonObj = JSON.parse(jsonStr);
idArr=jsonObj.id;
stateArr=jsonObj.State;
idArr.forEach(function(id) {
console.log(id);
});
stateArr.forEach(function(state) {
console.log(state);
})
hope this will help you
5 Comments
You can try this with jquery Mention jquery as :
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Code or script
var obj = $.parseJSON( '{\"id\" :[\"dddd\"],\"State\" :[\"TX\",\"IA\"]}' );
console.log(obj.id);
1 Comment
So once you have got the object, you have to get the array field on which you want to perform iteration. For Ex if you want to iterate over State, Check below:
for (var i=0;i<obj.State.length;i++)
{
obj.State[i] ;
}
Is this what you were looking for? If not, then pls be more clear.
JSON.parse, what is left to be achieved ?obj.idand you've got the array. Orobj.id.lengthfor the length of it (should be 1 here)idarray contains one item; an empty string