1

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.

J3STER
  • 1,027
  • 2
  • 11
  • 28
user7637864
  • 237
  • 3
  • 5
  • 15

3 Answers3

2
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

Jackson Baby
  • 398
  • 3
  • 4
  • 20
  • but the idArr.length is giving me 1. That should not be the case right? – user7637864 Mar 16 '17 at 05:16
  • 2
    idArr is a String array and it contains one empty String in its 0th index, That is why idArr.length is 1 – Jackson Baby Mar 16 '17 at 05:18
  • Can you please let me know how to get rid of that Empty String. I have tried (obj.id.isEmpty()) check . But its not working. @Jackson Baby – user7637864 Mar 16 '17 at 05:20
  • http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript – Jackson Baby Mar 16 '17 at 05:24
  • Use filter http://stackoverflow.com/questions/19888689/remove-empty-strings-from-array-while-keeping-record-without-loop/19888749#19888749 – Abhay Mar 16 '17 at 05:27
1

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);
Isaac
  • 11,409
  • 5
  • 33
  • 45
Arjun Prajapati
  • 263
  • 1
  • 2
  • 15
0

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.

Skeptic Scribbler
  • 527
  • 1
  • 6
  • 18