Iterating in a JSON in javascript - javascript

I have a JSON which looks like below.
[
{"Device":"Device1","Links"["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]
I want to iterate through it and in the loop i want to alert the values of Links field.
How can I achieve this.

If you have a json as a string you can use
var json = JSON.parse(jsonString);
this will return an object array on which you can iterate.
See more here

var arr = [
{"Device":"Device1","Links" ["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"}
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
];
for(var i=0;i<arr.length;i++){
var obj = arr[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
}
}

Say you have your string json:
var data = JSON.parse(json);
for(var i=0; i<data.length; i++) {
var links = data[i]['Links'];
for(var j=0; j<links.length; j++) {
//append this wherever
document.write(links[j]);
//if you're using jQuery, $('body').append(links[j]);
}
}

[
{"Device":"Device1","Links":["NewLink","NewLink2","NewLink3"],"GeographicLocation":"NewLocation"},
{"Device":"Device2","Links":["NewLink"],"GeographicLocation":"NewLocation"},
{"Device":"Device3","Links":["NewLink","NewLink2"],"GeographicLocation":"NewLocation"}
]
var json = JSON.parse(jsonString);
now it will work
you have missed ":" and " , " in your JSON string
near the first "Links": and }, add this

var json = [
{
"Device": "Device1",
"Links": [
"NewLink",
"NewLink2",
"NewLink3"
],
"GeographicLocation": "NewLocation"
},
{
"Device": "Device2",
"Links": [
"NewLink"
],
"GeographicLocation": "NewLocation"
},
{
"Device": "Device3",
"Links": [
"NewLink",
"NewLink2"
],
"GeographicLocation": "NewLocation"
}
];
for(var i=0; i<json.length ; i++)
{
console.log(json[i].Device);
console.log(json[i].Links);
// for links use another loop
for(var j=0; j<json[i].Links.length ; j++)
{
console.log(json[i].Links[j]);
}
console.log(json[i].GeographicLocation);
}

Related

Parsing json containing array of array gives 'undefined'

I am trying to access elements inside an array of the array in JSON but I am getting undefined.
Error - Uncaught TypeError: Cannot read property 'lsi_short_name' of undefined at line no. 9 $("#jsondata").append(
Code is shown below :
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
var obj = JSON.parse(data);
for(i=0;i<obj.response.length;i++) {
for (j=0; j < obj.response[i].length; j++) {
$("#jsondata").append("<li onclick=jsonDetails('"+obj.response[i][j][j+1]['lsi_short_name'] +"','"+ obj.response[i][j][j+1]['entities']+"','"+ obj.response[i][j][j+1]['attributes']+"')>"+obj.response[i][j][j+1]['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
Thanks in advance.
You key order is not serial wise, that's why you should not use j+1. So you can get the exact key first using Object.keys() then access the properties: Example:
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
//var data = '{"response": "[[{"1": {"attributes": [], "entities": [], "lsi_short_name": "a", "type": "process"}}, {"2": {"attributes": ["d"], "entities": ["c"], "lsi_short_name": "b", "type": "process"}}], [{"1": {"attributes": [], "entities": [], "lsi_short_name": "a", "type": "process"}},{"6": {"attributes": [], "entities": [], "lsi_short_name": "f", "type": "process"}}]]"}';
var obj = JSON.parse(data);
for(var i = 0; i < obj.response.length; i++) {
for (var j = 0; j < obj.response[i].length; j++) {
var key = Object.keys(obj.response[i][j])[0];
$("#jsondata").append("<li onclick=jsonDetails('" + obj.response[i][j][key]['lsi_short_name'] +"','"+ obj.response[i][j][key]['entities']+"','"+ obj.response[i][j][key]['attributes']+"')>"+obj.response[i][j][key]['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
You are trying to access the object beyond the length of the array. You also do not have any property named attributes.
You can first get the values from the object then use the index like the following way:
var data = '{"response":[[{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"5":{"type":"p","lsi_short_name":"E","entities":["term_Quantity"]}}], [{"1":{"type":"p","lsi_short_name":"A","entities":["term_Quantity"]}}, {"2":{"type":"p","lsi_short_name":"B","entities":["term_Quantity"]}}, {"4":{"type":"d","lsi_short_name":"D","entities":["term_Quantity"]}}, {"6":{"type":"p","lsi_short_name":"F","entities":["term_Quantity"]}}]]}';
var obj = JSON.parse(data);
for(let i=0;i<obj.response.length;i++){
for (let j=0; j < obj.response[i].length; j++) {
let o = Object.values(obj.response[i][j])[0];
$("#jsondata").append("<li onclick=jsonDetails('"+o['lsi_short_name'] +"','"+ o['entities'][0]+"')>"+o['lsi_short_name']+"</li>");
}
$("#jsondata").append("<br>");
}
function jsonDetails(sn, en){
console.log(sn + '::' + en)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="jsondata"></div>
Your for loop should look like below:
var obj = JSON.parse(data);
for(i=0;i<obj.response.length;i++){
var x = obj.response[i];
for (j=0; j < x.length; j++) {
//Assuming the keys are serial else you need to get all the keys using Object.keys method.
var keyName = (j+1).toString();
//Access various prop of your json like this --> x[j][keyName]["lsi_short_name"]
}
}

Javascript returns only keys but not values

The following is the data from the source file:
{
"dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#968513c8f0cc4249b7cfc2290ac967dc",
"dubbuseqsequential+block#f7f730a478144a74bd127f996d6dc4f5",
"dubbuseqsequential+block#91a0d5d7cd9649a3bdf057400e0a1c96",
"dubbuseqsequential+block#28b2b171b6734b13af29735796c5ad5a",
"dubbuseqsequential+block#192a150c8aab43b9bd236773ba60b414",
"dubbuseqsequential+block#26b3464dad42460ea66f9afe89770065"
],
"metadata": {
"display_name": "Introduction course orientation"
}
},
"dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd": {
"category": "chapter",
"children": [
"dubbuseqsequential+block#c95826a16f71405ba58319d23d250fc4",
"dubbuseqsequential+block#fe4e3b8b7cdd4fa0b9fe9090223b7125",
"dubbuseqsequential+block#44bbdee625dc465ebe725d2126ed0662",
"dubbuseqsequential+block#8d4daba07d4443f3b2a0b2506280ee2c",
"dubbuseqsequential+block#c68d9d3ba7de45b1b0770085e4f1f286",
"dubbuseqsequential+block#ccdca5b2aca94dbdabb3a57a75adf3fa"
],
"metadata": {
"display_name": "Module closing section"
}
}
}
The following javascript brings the top key values (i.e dubbuseqchapter+block#a7a5931f68d0482eaff2b7c9f9684e47,dubbuseqchapter+block#b2451e9195c5466db8b66f53ed06c9fd )
Javascript code
var obj = JSON.parse(jContent);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var row = createRowCopy(getOutputRowMeta().size());
var idx = getInputRowMeta().size();
row[idx++] = keys[i];
// Alert (keys.length);
putRow(row);
}
However, I am unable to get the values of the keys..(i.e. Category, Children and metadata) in this example.
I have tried Objects.values() but it returns null or object object in the Alert.
keys is an array of strings, each string being a property name.
You get the value for a property name in the usual way:
object[property_name]
i.e.
var value = obj[keys[i]];
this code shows how to navigate into parsed JsonData
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
console.log(obj[keys[0]].metadata.display_name);
this will print : Introduction course orientation
Or even this way to retrieve your subProperties
var obj = JSON.parse(textJson);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++){
console.log(keys[i]);
var subKeys = Object.keys(obj[keys[i]]);
for (var j = 0; j < subKeys.length; j++) console.log(subKeys[j] + " --> " + obj[keys[i]][subKeys[j]]);
}

How to fetch Dynamic keys from JavaScript Associative array?

I have a JSON string which I then convert into JSON Object by using jQuery. The string in question given below:
var json = [
{
"1240": [
"Order1",
"user1"
]
}
]
Here key 1240 is Dynamic and I can't do something like json[0]["1240"] When I do something like:
for(var f in json )
{
alert(f);
}
Then it returns "0"
How do I fetch 1240 here?
Because it's an array of objects.
http://jsbin.com/umaWoge/1/
Try this
var json = [
{
"1240": [
"Order1",
"user1"
]
}
];
for (var i = 0; i < json.length; i++)
{
for(var f in json[i])
{
alert(f);
}
}
try this also.
var json = [
{
"1240": [
"Order1",
"user1"
]
}
];
for (var i in json)
{
for(var f in json[i])
{
alert(f);
}
}

Javascript: Getting all existing keys in a JSON array

I have a JSON array like below:
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
I don't know which keys does exists in this array.
I want to get all the existing key from the array.
It should be possible something like this:
for(i=0;i<jsonArray.lenght;i++){
// something like- key = jsonArray[i].key
// alert(key);
}
Please tell me the method or way to get all keys existing in Json array.
Regards
Why don't you use a
var jsonObject = {"k1":"v1","k2":"v2","k3":"v3","k4":"v4","k5":"v5"}
instead of your
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
? Then the solution would be so simple: Object.keys(jsonObject).
Try this:
var L = jsonArray.length;
for (var i = 0; i < L; i++) {
var obj = jsonArray[i];
for (var j in obj) {
alert(j);
}
}
I've also made some modifications of your current code (like length caching).
Loop through the object properties, and select the first "real" one (which given your data schema should be the only real one).
var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
for (var i = 0; i < jsonArray.length; i++) {
for (var prop in jsonArray[i]) {
if (jsonArray[i].hasOwnProperty(prop)) {
var key = prop;
break;
}
}
alert(key);
}
See How to loop through items in a js object? for an explanation of why it's important to use hasOwnProperty here.
Try this:
jsonArray.reduce(function(keys, element){
for (key in element) {
keys.push(key);
}
return keys;
},[]);
This should also work for multiple keys in the array objects.
If you're supporting old browsers that don't have reduce and map, then consider using a shim.
var id = { "object": "page", "entry": [{ "id": "1588811284674233", "time": 1511177084837, "messaging": [{ "sender": { "id": "1393377930761248" }, "recipient": { "id": "1588811284674233" }, "timestamp": 1511177084553, "message": { "mid": "mid.$cAAX_9pLcfu1mCnGmiVf2Sxd2erI2", "seq": 1882, "text": "a" } }] }] };
function getKey(obj, data) {
//#author dvdieukhtn#gmail.com
var data = data || [];
if (obj) {
var keys = Object.keys(obj);
for (var pos in keys) {
console.log();
data.push(keys[pos]);
if ((obj[keys[pos]].constructor === Array)) {
for (var i = 0; i < obj[keys[pos]].length; i++) {
getKey(obj[keys[pos]][i], data);
}
}
else if (obj[keys[pos]].constructor === Object) {
getKey(obj[keys[pos]], data);
}
}
return data;
}
}
console.log(getKey(id));

loop a JS Object

I have this JS object:
{
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
}
how can I loop through these items to get comment value ("comment":"text")?
You don't really need to loop to get it. Just do...
var obj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
var text = obj.data.nid[0].comment;
Or if there are several, you can use forEach...
obj.data.nid.forEach(function(val,i) {
alert( val.comment );
});
Or a traditional for loop...
for( var i = 0; i < obj.data.nid.length; i++ ) {
alert( obj.data.nid[i].comment );
}
Or if you want to build an Array, use map...
var arr = obj.data.nid.map(function(val,i) {
return val.comment;
});
Or again a traditional for loop...
var arr = []
for( var i = 0; i < obj.data.nid.length; i++ ) {
arr.push( obj.data.nid[i].comment );
}
Given:
var obj = {
"data": {
"nid": [{
"cid": "32",
"uid": "780",
"comment": "text"
}]
},
"request_status": "found"
};
The direct way to retrieve the comment is:
obj["data"]["nid"][0]["comment"]
// or
obj.data.nid[0].comment
As far as "looping" through the items to get the value, I'm not sure how a loop makes sense. Are you saying you might not know the structure of the object but you know it will have a "comment" field in there somewhere?
The "nid" array only has one item in it - if this was just a sample but really you'll have an array with more values you can loop through that array:
var nid = obj["data"]["nid"], // get a direct reference to the array to save
i; // repeating obj.data.nid everywhere
for (i=0; i < nid.length; i++) {
// do something with the comment in the current item
console.log(nid[i]["comment"]);
}
If you're just referring to that specific object (or if every object you are working with follows that same pattern), then you can just access the value directly:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
alert(theObj.data.nid[0].comment);
If you want to do something iterative, then perhaps try this:
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
for (var index = 0; index < theObj.data.nid.length; index++) {
var item = theObj.data.nid[index];
if (item.comment) {
alert(item.comment);
}
}
Or if you really want to do the entire thing iteratively:
window.searchObj = function(theObj) {
if (theObj.comment) {
alert(theObj.comment);
}
if (theObj instanceof Array) {
searchArray (theObj);
}
else if (theObj instanceof Object) {
for (var key in theObj) {
searchObj(theObj[key]);
}
}
};
window.searchArray = function(theArray) {
for (var index = 0; index < theArray.length; index++) {
var item = theArray[index];
searchObj(item);
}
};
var theObj = {"data":{"nid":[{"cid":"32","uid":"780","comment":"text"}]},"request_status":"found"};
searchObj(theObj);

Categories

Resources