Get the number of parent objects in a json object using jquery - javascript

Following is the JSON array, I want to get number of parent objects and then run for loop on them to get each object value.
It should give total count 2 as I have two parent objects - canvas0 and canvas1.
{"canvas0":
"{"objects":
[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage1","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"
,"canvas1":"{"objects":[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage2","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"}

As everyone said, your JSON is invalid. The same valid JSON in minimal would look like the following.
var json = {
"canvas0": {
"objects": [
{
"type": "textbox",
"originX": "left"
}
],
"background": "#000"
},
"canvas1": {
"objects": [
{
"type": "select",
"originX": "right"
}
]
}
};
To be able to iterate thru, you don't need the count of top level keys. And moreover, a JSON object doesn't have the length property. All you need to do is, use for...in loops and display the key/values accordingly. Here is an example of how you can do it. Bear in mind that this only works with your specific case as the loop needs changing as and when the JSON levels change.
alert ( "Length of top level keys: " + Object.keys(json).length );
for (var key in json) {
var canvas = json[key];
for (var key2 in canvas) {
if (canvas[key2] instanceof Array) {
var object = canvas[key2][0];
for (var key3 in object) {
alert (key3 + ": " + object[key3]);
}
} else {
alert (key2 + ": " + canvas[key2]);
}
}
}
Here is a working demo with the complete code.

Related

How to access each key and value of json in JQuery or JavaScript [duplicate]

nested json structure
Json Structure:
{
"id": "30080",
"dataelements": {
"Name": "abc",
},
"children": [
{
"id": "33024",
"dataelements": {
"Name": "a",
},
"children": [
{
"id": "33024",
"dataelements": {
"Name": "b"
},
"children": [
{
"id": "33024",
"dataelements": {
"Name": "z"
},
"children": []
}
]
}
]
},
{
"id": "4800",
"dataelements": {
"Name": "d"
},
"children": [
{
"id": "4800",
"dataelements": {
.........................
I have my nested json data as shown in the image. For every child object, I create a node model. A child object can have additional child objects inside it.
if (ele == "dataelements")
{
var categoryNode = new NodeModel(
{
label: row.dataelements.Name,
icons: [{ iconName: 'product'}],
grid: row[ele]
});
}
if(ele == "children")
{
var subCategoryNode;
var subCategoryIndex = 1;
for (var i = 0, len = row.children.length; i<len; i++)
{
subCategoryNode = new NodeModel(
{
label: row.children[i].dataelements.Name,
icons: [{
iconName: '3dpart' }],
grid: row.children[i].dataelements
});
categoryNode.addChild(subCategoryNode);
}
}
This code handles only one level of child nodes.
How do I check for the inner children when I don't know exactly how many child levels are nested inside?
A quick run down on recursive functions and a gotcha to look out for
Recursive functions are great for nested data
They call themselves for each iteration of the input until it hits a base case
They can be tricky to wrap your head around at first
Recursive functions can hit the call stack limit if used poorly or the input is monstrous in size
Look out for variables used in the recursive calls, use let keyword to tell javascript to set the variable in the current scope
The Solution
Let's assume your JSON has been validated and this is the structure in the example below.
If I want to iterate through all elements in the JSON, I want to use a recursive call to make it neat, and simple to debug and simple to build on.
Here is an example of iterating through your given example JSON to print out an exploded view.
How to use the below code
Copy the recursiveSearch function
Call the recursiveSearch function passing in your JSON
Modify it to your needs, I gave you something to build on
CODE
var someJson = {"id": "30080","dataelements": {"Name": "abc"},"children": [{"id": "33024","dataelements": {"Name": "a"},"children": [{"id": "33024","dataelements": {"Name": "b"},"children": [{"id": "33024","dataelements": {"Name": "z"},"children": []}]}]}, {"id": "4800","dataelements": {"Name": "d"},"children": []}]};
//we set level to 0 (optional variable) this means we can omit it in the inital call for neat code
function recursiveScan(json, level=0)
{
//we store all of the output in a log and keep a track of the level to determine indenting
var log = "";
var indent = "";
//based on the current level of the recursion, we indent the text to make it readable
for (let i=0; i<level; i++)
{
indent += "  ";
}
//avoid any bad json or invalid data by checking if the name and id is null
if(json.dataelements.Name != null && json.id != null)
{
//we know there is a valid element, write the name and id
log += indent + "ID: " + json.id + "<br>";
log += indent + "Name: " + json.dataelements.Name + "<br>";
//if there is any children
if(json.children.length > 0)
{
//just for neatness, lets draw the paranthesis
log += indent + "{" + "<br>";
//increase the level
level++;
//for each child, recursively call this function to get the next level of children if available
for(let t=0; t<json.children.length; t++)
{
log += recursiveScan(json.children[t], level);
}
//we are dropping our recursion level now, getting ready to return;
level--;
//close the paranthesis for neatness
log += indent + "}" + "<br>";
}
}
//return the final log
return log;
}
//now lets test the code
document.write(recursiveScan(someJson));
The above code produces
ID: 30080
Name: abc
{
  ID: 33024
  Name: a
  {
    ID: 33024
    Name: b
    {
      ID: 33024
      Name: z
    }
  }
  ID: 4800
  Name: d
}
Now a simple run-down without all the noise
function recursiveScan(json)
{
if(json.dataelements.Name != null && json.id != null)
{
//here you have access to id and dataelements
if(json.children.length > 0)
{
for(let t=0; t<json.children.length; t++)
{
//here you have access to each child as json.children[t]
//you could do the logic for the current child
//then pass the current child to the recursive function
recursiveScan(json.children[t]);
}
}
}
return true;
}

Iterating over a json array whose key value is dynamic

I have a json structure as:
{
"TestCaseList": [
{
"TC_1": {
"name":"verifyloginpagedetails",
"value":"2"
},
"TC_2": {
"name":"verify registration page details",
"value":"3"
}
}
],
"Summary": {
"v":[
{
"name":"over the ear headphones - white/purple",
"value":1
}
]
}
}
How to extract the values name, value of TC_1 , TC_2 where TC_1 is dynamic i.e. key of TestCaseList?
You can use the Object.keys method to get an array of the keys of an object.
With a single object in the array at "TestCaseList" in your JSON object, this will work:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
If, however, the array at "TestCaseList" contains more than one one element, you can use this to get each set of keys in an individual array:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
I'm sure a more elegant solution exists, but this will do the trick.
var myObj = {
"TestCaseList":
[{
"TC_1":
{"name":"verifyloginpagedetails",
"value":"2"},
"TC_2":
{"name":"verify registration page details",
"value":"3"}
}],
"Summary":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
}
}
let testCaseListKeys = Object.keys(myObj.TestCaseList[0]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
console.log(tclKey + "\'s name = " + myObj.TestCaseList[0][tclKey].name);
console.log(tclKey + "\'s value = " + myObj.TestCaseList[0][tclKey].value);
}
The console.logs are your output. The important values there are the myObj.TestCaseList[0][tclKey].name and the myObj.TestCaseList[0][tclKey].value
** UPDATE **
After answering the question Ananya asked how to do this same thing if the object had a different structure.
Updated Object:
var myObj2 = {
"TestCaseList":
[{
"TC_1":{
"name":"verifyloginpagedetails",
"value":"2"}
},
{
"TC_2":{
"name":"verify registration page details",
"value":"3" }
}],
"Summary":
{
"v":[ {"name":"over the ear headphones - white/purple","value":1} ]
}
}
Updated JavaScript:
for(x=0;x<myObj2.TestCaseList.length;x++) {
let testCaseListKeys = Object.keys(myObj2.TestCaseList[x]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
//console.log(tclKey);
console.log(tclKey + "\'s name = " + myObj2.TestCaseList[x][tclKey].name);
console.log(tclKey + "\'s value = " + myObj2.TestCaseList[x][tclKey].value);
}
}

JSON Object many errors. Help out

I have made a JSON object and getting so many errors. I am new to JSON so kindly help. Posting here with the screenshots.
Any help would be appreciated.
[![var data\[\]= {"cars":
"Honda":\[
{"model":"Figo" },
{"model":"City"}
\],
"Audi": \[
{"model":"A6"},
{"model":"A8"}
\]
}
data.cars\['Honda'\]\[0\].model
data.cars\['Honda'\]\[1\].model
data.cars\['Audi'\]\[0\].model
ata.cars\['Audi'\]\[1\].model
for (var make in data.cars) {
for (var i = 0; i < data.cars\[make\].length; i++) {
var model = data.cars\[make\]\[i\].model;
alert(make + ', ' + model);
}
}][1]][1]
Using JSONformatter and validator site for checking my code.
Since you mentioned
I am totally novice for JSON
I would like to explain you this completely.
There are little bit of syntax errors in the way you are doing this. You are actually doing a for loop inside a javascript object which will obviously break. If your intention is to alert all the models of all the make, then here is how you do it..
initially you have this
var data = {
cars:{
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
}
You have a variable called data which is a object ({} refers to object) and this object has a property called cars and this property holds a object({} refers to object). Now this object has 2 properties Honda and Audi. Each of this properties are of type array ([] refers to array). And this each array further contains list of objects.
So once you are clear with the above point. Let manipulate the object you have.
Do a forloop to get all the properties of the cars object and when we have hold of each property lets loop its array and then extract the model property value.
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
alert(make + ', ' + model);
}
}
Also dont get confused with Javascript Object and JSON....
In the above example the variable data is Javascript Object and when you do JSON.strinfigy(data) you are converting this Javascript object into string format and that string format is called JSON...
A Demo Fiddle to help you understand better.
Imho it's more like :
var cars = {
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
If you want a huge JSON object storing many cars attributes arrays.
Why do you use these "/" everywhere ?
(PS : if you wanna see some examples -> http://json.org/example.html)
I believe this is the structure your looking for:
cars={
make:{
honda:[
{
model:"accord",
color:"black",
cylinders: "6",
year:"2012"
},
{
model:"civic",
color:"white",
cylinders: "4",
year:"2015"
}
],
acura:[
{
model:"integra",
color:"red",
cylinders: "4",
year:"1992"
},
{
model:"RSX",
color:"Metallic Blue",
cylinders: "4",
year:"2016"
}
],
audi:[
{
model:"R8",
color:"white",
cylinders: "8",
year:"2015"
},
{
model:"A8",
color:"red",
cylinders: "8",
year:"2016"
}
]
}
};
document.addEventListener('DOMContentLoaded',()=>{
var models=[],colors=[],cylinder=[],year=[]; //INSTANTIATE ARRAYS
for(p in cars.make){ //LOOP THROUGH OBJECT PROPS (CARS.MAKE)
cars.make[p].forEach((o)=>{ //LOOP THROUGH (CARS.CARS.PROPS) PUSH OBJ INTO ARRAYS
models.push(o.model);
colors.push(o.color);
cylinders.push(o.cylinders);
year.push(o.year);
});
console.log(models);
console.log(colors);
console.log(cylinders);
console.log(year);
});

Iterating over JSON object

I'm having some troubles iterating in a json object.
I'm currently saving the table properties of a some web page in a cookie.
The value of the cookie is an array of objects which I serialize.
The typical value of an array with 2 entries is something like:
cookieValue=["{ "PageID": "1391", "PageSize": "100"}", "{ "PageID": "2341", "PageSize": "50"}"]
My problem is iterating in this array now. I want to be able to check if there is any duplicate entry to update its PageSize (if applicable) or to read it in order to set the page size when a user goes back to the same page.
I've tried this so far:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key]);
}
}
which give me an output like:
0 -> { "PageID": "1391_tabela", "PageSize": "100"}
1 -> { "PageID": "1391_tabela", "PageSize": "50"}
2 -> { "PageID": "1391_tabela", "PageSize": "10"}
My question is how am i able to access the value of PageID in each entry.
Thanks in advance
I am not sure if I understand you correctly but I think you should just use
cookieValue[key]["PageID"]
together:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key] + " -> " + cookieValue[key]["PageID"]);
}
}
It seems that you need to get the object by the PageId. Here is a function
function getPageById(pageId) {
for (var pageObj in cookieValue) {
if (pageObj.PageId === pageId)
return pageObj;
}
}
If you only want to access the value of PageId in each entry, you can view example here :
var cookieValue=[{ "PageID": "1391", "PageSize": "100"}, { "PageID": "2341", "PageSize": "50"}];
for (key in cookieValue) {
alert(cookieValue[key]["PageID"]);
}
JSFIDDLE
Manipulate the data using a javascript array for easier code.
One way that should work for you:
convert your JSON into a javascript array using:
var mycookieArray = JSON.parse(cookieValue);
Iterate through it with:
for(String s : myCookieArray)
{
console.log(s.PageID);
}

How can I divide this jQuery data array?

I have the following javascript array:
[{
"id": "115",
"poster": "809",
"post": "alfa"
}, {
"id": "127",
"poster": "808",
"post": "beta"
}]​
What do I need to do in order to extract the values into usable variables?
Try this,
var arr = [{"id":"115","poster":"809","post":"alfa"},{"id":"127","poster":"808","post":"beta"}];
for (i = 0; i < arr.length; i++)<br/>
document.write("id: " + arr[i].id + " poster: " + arr[i].poster + " post: " + arr[i].post + "<br/>");
What you have is an array with two elements
data = [a,b]
where both elements a and b are objects each having three fields (id,poster,post).
Recall that to access an element in the array at position i you simply write data[i] (this will access the ith element in your array i.e. one of the objects).
In order to access a field of the object a you simply use a.fieldName. For example a.id will access id field of object a. If you combine them both you can get data[i].fieldName to access field of specific object (for example data[0].id will return "115").
As a side note, array structures are iterable:
for(var i = 0;i<data.length;i++){
id = data[i].id;
post = data[i].post;
poster = data[i].poster;
document.write(id+" "+post+" "+poster+"<br/>");
}
UPDATE: Example on jsFiddle

Categories