• 0

Parsing JSON in Javascript


Question

Hello all,
I am new to Javascript and I am trying to parse the following JSON. But nothing happens so I'm assuming there is some error.

I am also trying to figure out how to loop through the JSON and access the data, but I can't even get it to load.

var text = [
    {"ITEM ONE":[
            {"SUB ONE":[
                    "one",
                    "two"
                ]
            },
            {"SUB TWO":[
                    "three",
                    "four"
                ]
            }

    ]},


    {"ITEM TWO":[
            {"SUB THREE":[
                    "five"
                ]
            },
            {"SUB FOUR":[
                    "six"
                ]
            }

    ]}
];

var obj = JSONArray.parse(text);
JSONObject jo = inputArray.getJSONObject(0);
document.getElementById("demo").innerHTML = obj(0);

Here are the variations that I've tried. For var obj, I tried using just JSON.parse(). I also tried not have the jo var.

 

And for the JSON itself, I also tried adding the following to each line 'JSON_HERE'+  To try and deal with the multiline JSON.  I also put it all on one line.

 

I'm not sure what to do. Could someone show me the problem and some code that accesses the element and a snippet that loops through it?

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

...

 

 

 

Couple of issues:

 

1. You're assigning a real object to "text", not actual text that needs parsing

2. JSONArray isn't a type, use JSON.parse()

3. You never define an object called "inputArray"

4. Don't provide a type when creating an variable (JSONObject jo)

 

Below is a working demo that parses your JSON (as text) and writes a value from it into a <P> tag.

 

One more thing When testing javascript it's always helpful to load up your browsers developer tools (CTRL SHIFT I in Chrome, F12 in IE) and step though and inspect your code. You can learn a lot from it. 

<!doctype html>
<html>
<head>
 
</head>
<body>
<p id="demo"></p>
 
 
<script>
var text = "[\
    {\"ITEM ONE\":[\
            {\"SUB ONE\":[\
                    \"one\",\
                    \"two\"\
                ]\
            },\
            {\"SUB TWO\":[\
                    \"three\",\
                    \"four\"\
                ]\
            }\
    ]},\
    {\"ITEM TWO\":[\
            {\"SUB THREE\":[\
                    \"five\"\
                ]\
            },\
            {\"SUB FOUR\":[\
                    \"six\"\
                ]\
            }\
    ]}\
]";
 
var obj = JSON.parse(text);
var jo = obj[0];
document.getElementById("demo").innerText = obj[0]["ITEM ONE"][0]["SUB ONE"][0];
</script>
 
</body>
</html>
Link to comment
Share on other sites

This topic is now closed to further replies.