Aniket Sahrawat Aniket Sahrawat - 13 days ago 6
Javascript Question

How to print Arrays from JSON string

I am new to JSON and I can't really figure out how to print the key value pair, this is my JSON code:



{
"name": "open",
"auto": true,
"contexts": [],
"userNebolaK": [
{
"data": [
{
"text": "open"
}
],
"isTemplate": false
}
],
"responses": [
{
"resetContexts": false,
"action": "doSomeAction",
"affectedContexts": [],
"parameters": [
{
"required": false,
"name": "para"
}
],
"this": "one moment please"
}
],
"state": "UNKNOWN",
"priority": 500000,
"webhookUsed": false
}





and HTML



<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title> </title>
<script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
</head>
<body>
<script type="text/javascript">
//$.getJSON('testing3.json', function(dataE) {
// document.write(dataE.user);
//})
$.getJSON('testing.json', function(data) {
$.each(data, function(target1) {
console.log(target1);
})
})
</script>
</body>
</html>





I need to print Value corresponding to text in=> UserNebolaK-data-text
also UserNebolaK-isTemplate

Thanks in Advance!

Answer

You can access these 2 values using dot notation. Assuming your json is stored in a variable named jsonData, it would look like this:

console.log(jsonData.userNebolaK.data[0].text);

and

console.log(jsonData.userNebolaK.isTemplate);

It's worth noting that userNebolaK.data is an array which is why we need the [0] in the code above to access it, but if there will be more than one element in that array, you might need to do a bit of logic:

for (var i=0; i<jsonData.userNebolaK.data.length; i++) {
    console.log(jsonData.userNebolaK.data[i].text);
}

This for loop will go through all the values in the userNebolaK.data array and log each one. If you want to find a specific one, you can then apply a condition with something like an if statement to each iteration of the loop.

This is all fairly basic javascript stuff, so if you're finding this difficult you'll probably want to have a quick look at some Javascript basics tutorials, as well as read a bit about for, if, arrays, and Objects in javascript.