Parsing json containing array of array gives 'undefined' - javascript

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"]
}
}

Related

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]]);
}

JavaScript - converting object key value pairs to JSON

I have a javascript object with 6 key value pairs:
My_Type_1:"Vegetable"
My_Type_2:"Fruit"
My_Type_3:"Dessert"
My_Value_1: "Carrot"
My_Value_2: "Apple"
My_Value_3: "Cake"
I want to construct JSON out of the above object such that it generates the following:
[{"Vegetable":"Carrot"},{"Fruit":"Apple"},{"Dessert":"Cake"}]
EDIT:
for (j=0;j<3;j++)
{
var tvArray = new Array();
var sType = 'My_Type_'+j+1;
var sValue = 'My_Value_'+j+1;
tvArray['Type'] = JSObject[sType];
tvArray['Value'] = JSObject[sValue];
}
The json.stringify doesn't produce the desired output as listed above.
How do I do this?
Thanks
You need to put parenthesis around j + 1. What you have now gives you 'My_Type_01' and so on.
var obj = {
My_Type_1:"Vegetable",
My_Type_2:"Fruit",
My_Type_3:"Dessert",
My_Value_1: "Carrot",
My_Value_2: "Apple",
My_Value_3: "Cake"
};
var pairs = [], pair;
for(var j = 0; j < 3; j++) {
pair = {};
pairs.push(pair);
pair[obj['My_Type_' + (j+1)]] = obj['My_Value_' + (j+1)];
}
console.log(JSON.stringify(pairs));

Iterating in a JSON in 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);
}

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs

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));

Categories

Resources