How to read value from JSON object - javascript

I'm sorry for the specificity of this situation, but I just can't wrap my head around the issue.
I've created the following JSON file:
{"characters":[
{"name":"battler", "sprites":
[{"img":"but_a11_aseru1.png","img":"but_a11_komaru1.png","img":"but_a21_majime1.png","img":"but_b11_majime1.png"}]
},
{"name":"eva", "sprites":
[{"img":"eva_a11_akire1.png","img":"eva_b11_majime1.png","img":"eva_b21_naku1.png","img":"eva_b22_warai1.png"}]
}
]}
And I am attempting to load it with this code, just to echo the value for "img" for the first "sprites" in each entry for now:
$.getJSON( "./char.json", function( data ) {
for (i = 0;i < data.characters.length;i++) {
alert(JSON.stringify(data.characters[i].sprites[0]));
}
});
For example: I'm trying to get it to return "but_a11_aseru1.png" for the first iteration of the loop and "eva_a11_akire1.png" for the second.
I've tried data.characters[i].sprites[0], only to get a value of {"img":"but_a11_aseru1.png"} for the first (and similar for the second). data.characters[i].sprites.img turns up as undefined. I could use .split at the ":" but I want to understand how to properly use JSON.
Can someone point out what I'm doing wrong? Thank you.

To get expected output ("but_a11_aseru1.png" for the first iteration) with your code, you need to make sprites an array with items corresponding to individual images:
{"characters":[
{"name":"battler", "sprites": [
"but_a11_aseru1.png",
"but_a11_komaru1.png",
"but_a21_majime1.png",
"but_b11_majime1.png"
]},
{"name":"eva", "sprites": [
"eva_a11_akire1.png",
"eva_b11_majime1.png",
"eva_b21_naku1.png",
"eva_b22_warai1.png"
]}
]}
and
alert(JSON.stringify(data.characters[i].sprites[0]));
or
{"characters":[
{"name":"battler", "sprites": [
{"img":"but_a11_aseru1.png"},
{"img":"but_a11_komaru1.png"},
{"img":"but_a21_majime1.png"},
{"img":"but_b11_majime1.png"}
]},
{"name":"eva", "sprites": [
{"img":"eva_a11_akire1.png"},
{"img":"eva_b11_majime1.png"},
{"img":"eva_b21_naku1.png"},
{"img":"eva_b22_warai1.png"}
]}
]}
and
alert(JSON.stringify(data.characters[i].sprites[0].img));

Your issue is that your original JSON isn't well formed. You declare "sprites" to be an array, but then all of the img keys belong to a single object. Fixed this by making sprites an array of objects instead of an array of a single badly-formed object.
{
"characters": [{
"name": "battler",
"sprites": [{
"img": "but_a11_aseru1.png",
"img": "but_a11_komaru1.png",
"img": "but_a21_majime1.png",
"img": "but_b11_majime1.png"
}]
}, {
"name": "eva",
"sprites": [{
"img": "eva_a11_akire1.png",
"img": "eva_b11_majime1.png",
"img": "eva_b21_naku1.png",
"img": "eva_b22_warai1.png"
}]
}]
}
The below code works for me. I used jQuery's $.each() function, but you could have realistically used anything you wanted to loop through the items.
var json_data = {
"characters": [{
"name": "battler",
"sprites": [{
"img": "but_a11_aseru1.png"
}, {
"img": "but_a11_komaru1.png"
}, {
"img": "but_a21_majime1.png"
}, {
"img": "but_b11_majime1.png"
}]
}, {
"name": "eva",
"sprites": [{
"img": "eva_a11_akire1.png"
}, {
"img": "eva_b11_majime1.png"
}, {
"img": "eva_b21_naku1.png"
}, {
"img": "eva_b22_warai1.png"
}]
}]
};
$.each(json_data.characters, function(i, character) {
console.log(character.name, " ", character.sprites[0].img);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You should use a different structure for the sprites, currently you have an array with one object with several keys img which are the same, Browsers will only show the last one, the rest will be omitted.
var data = {
"characters": [
{
"name":"battler",
"sprites": [
{"img":"but_a11_aseru1.png"},
{"img":"but_a11_komaru1.png"},
{"img":"but_a21_majime1.png"},
{"img":"but_b11_majime1.png"}
]
},
{
"name":"eva",
"sprites": [
{"img":"eva_a11_akire1.png"},
{"img":"eva_b11_majime1.png"},
{"img":"eva_b21_naku1.png"},
{"img":"eva_b22_warai1.png"}
]
}
]
};
$.each(data.characters, function(i, char) {
$.each(char.sprites, function(j, sprite) {
console.log(sprite.img)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

check if item exists in json file then get it if exists. And if not complete executing the code

I get a json file from outer link by ajax call. i want to check element is exists in this json file or not and get it if exists. because it changes every time and items increases or decreases. If I get item and this item not existing, I get error and the code not complete. i want to check this item json.children[1].children and json.children[2].children ,..... if exists.
{
"num": 1,
"name": "aa",
"properites": [
{
"name": "prop1",
"value": "value1"
}
],
"children": [
{
"num2": 1,
"name2": "name2",
"properites": [
{
"name": "name",
"value": "value"
}
],
"children": []
},
{
"name": 1,
"num": "1",
"attributes": [
{
"name": "name",
"value": "value"
}
],
"children": []
.......................... big json file
I have tried to get these Items and set in local storage to use in table by this:
localStorage.setItem("row1-item1", json.children[1].children);
localStorage.setItem("row1-item2", json.children[2].children);
localStorage.setItem("row1-item3", json.children[3].children);
localStorage.setItem("row1-item4", json.children[4].children);
localStorage.setItem("row2-item1", json.name[1].children);
localStorage.setItem("row2-item2", json.name[2].children);
localStorage.setItem("row2-item3", json.name[3].children);
localStorage.setItem("row2-item4", json.name[4].children);
the problem here is if json.children[4].children not existing the code not complete the next line and jump out of ajax call even if json.name[1].children is exists. I tried try/catch but not solved it
Try to use map
json.children.map((children,index)=>{
localStorage.setItem('row${index}-item${index}`, children);
}
Or you can use forEach or for loop instead of map.

How to Get data in Json using javascripts?

Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.

Dynamically add array elements to JSON Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!

Javascript looping through elements and adding to table

I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.
Here is an example:
var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},
This is the structure of the elements. So far I've used this:
document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;
to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.
I would consider you to look at http://underscorejs.org/.
it provides a bunch of utility functions that could help you,
for example, _.each() helps you loop through JSON properties.
for the sample objects you've given (after completing the missing brackets at the end),
_.each(Table.groups[0].standings[0].stats, function(stats){
console.log(stats['name']+","+stats['value'])
})
gives me:
gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37
how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).
I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :
http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
http://scriptble.com/2011/01/28/underscore-js-templates/
I guess your question is about filtering the values of the array standings. In order to do that you can use the jQuery grep function (if you want to use jQuery).
For example you can write:
var arr = $.grep(Table.groups[0].standings[0].stats, function(d){return d.value>25})
Which will give
arr = [{"name": "gf","value": 64}, {"name": "ga", "value": 37},{"name": "gd", "value": 27},{"name": "pts", "value": 37}]
If this is not what you meant, can you please create a jsFiddle with a sample of what you want?
Depending on what you want to do with the results, you can go over the object using a scheme like:
var groups, standings, stats, value;
groups = Table.groups;
// Do stuff with groups
for (var i=0, iLen=groups.length; i<iLen; i++) {
standings = groups[i].standings;
// Do stuff with standings
for (var j=0, jLen=standings.length; j<jLen; j++) {
stats = standings[j];
// Do stuff with stats
for (var k=0, kLen=stats.length; k<kLen; k++) {
value = stats[k].value;
// Do stuff with value
}
}
}
Of course I have no idea what the data is for, what the overall structure is or how you want to present it. But if you have deeply nested data, all you can do is dig into it. You might be able to write a recursive function, but it might also become very difficult to maintain if the data structure is complex.

JSON parsing in JS

I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on

Categories

Resources