How to get json data properly in javascript - javascript

I'm trying to get the data inside of "attributes" in these json format, but I always get undefined
{ "data": [
{ "attributes":
{
"id":"4977",
"book_id":"651284829",
"provider_id":"1",
"title":"\u96e8\u8272\u30b3\u30b3\u30a2",
"author":"IAM, K.K.",
"price":"170.00",
"rating":"4"
},
...
}
}
This is my code which always returns undefined:
for ( var obj in json.data) {
var att = obj.attributes;
html += "<p>" + att.author + "</p>";
}

You're iterating over the keys of the properties of json.data, not the values of those properties.
Change
var att = obj.attributes;
to
var att = json.data[obj].attributes;
To make it clearer, a different name could be used :
for (var key in json.data) {
var obj = json.data[key];
var att = obj.attributes;
html += "<p>" + att.author + "</p>";
}

Related

Match key/values in JSON object

I have a school project where we are learning JSON. What I am trying to do is figure out how I can match keys with other keys that exist in another object property.
I'm using an old api to pull nfl player information. Here is an example of the url to pull the data:
http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2018&week=16&format=json
I'm using AJAX to call the data and stringify the results into a table.
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
var tbl = $("<table>");
$(tbl).addClass("table");
var objCount = JSON.stringify(response.players.length);
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th>
<th>Player</th><th>Stat</th></tr></thead><tbody>");
for (p = 1; p < 2; p++) {
var id = response.players[p].id;
var team = response.players[p].teamAbbr;
var pos = response.players[p].position;
var plyr = response.players[p].name;
var stat = JSON.stringify(response.players[p].stats);
var plyrStatsObjLen =
JSON.stringify(response.players[p].stats.length);
console.log("statObjLength: " + plyrStatsObjLen);
$.each(response.players[p].stats, function(key, value) {
console.log(key + ": " + value);
});
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + stat + "</td>");
}
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
});
Here is a fiddle of what I am doing:
https://jsfiddle.net/kenneth2k1/kcf5duLr/
If you notice the results, I have the stats property separated out in its own column, but it is still in the object's key/value structure.
Now, here is another url that has what each stat is:
https://api.fantasy.nfl.com/v1/game/stats?format=json
"stats": [
{
"id": 1,
"abbr": "GP",
"name": "Games Played",
"shortName": "GP"
},
{
"id": 2,
"abbr": "Att",
"name": "Passing Attempts",
"shortName": "Pass Att"
},
{
"id": 3,
"abbr": "Comp",
"name": "Passing Completions",
"shortName": "Pass Comp"
}, ... and so on
So for example key ID "1" corresponds with "Games Played" from the stat reference object.
I am new to all this, so what I can't wrap my head around is if I wanted to sub out the keys in my output with the corresponding name value from the stats reference object, how would I do that?
For example from the jsfiddle output, Instead of
{"1":"9","13":"1"}
It would say
Games Played: 9, Rushing Attempts: 1
I hope that makes sense. Basically I'd like to learn how to match keys in one JSON object with the key values in another.
Thank you very much for assistance.
You could nest your second AJAX call in the success function of your first call, then put your variable assignments and table creation into the second success function. Inside the second success function you'd use simple for loops to match each numerical statistic from the player data with the correct name of the statistic in the statistics data, like this:
$(document).ready(function () {
var statType = "seasonStats";
var season = "2018";
var week = "15";
var playersURL = "https://api.fantasy.nfl.com/v1/players/stats?format=json" + "&statType=" + statType + "&season=" + season + "&week=" + week;
var statURL = "https://api.fantasy.nfl.com/v1/game/stats?format=json";
// Now we get the stats
$.ajax({
url: statURL,
method: "GET",
success: function (response) {
const stats = response.stats;
// Then we get the players
$.ajax({
url: playersURL,
method: "GET",
success: function (response) {
const players = response.players;
// Now we do the rest of the logic
// Here's our table creation and header
var tbl = $("<table>");
$(tbl).addClass("table");
$(tbl).append("<thead><tr><th>ID</th><th>Team</th><th>POS</th><th>Player</th><th>Stat</th></tr></thead><tbody>");
// Here's where we create variables for each individual player
for (p = 0; p < 1; p++) {
let id = players[p].id;
let team = players[p].teamAbbr;
let pos = players[p].position;
let plyr = players[p].name;
// We create an empty object to hold the named statistics we're about to find
let statistics = {};
// Now we'll loop over the players and statistics to get names for all the stats
playerStats = players[p].stats;
for (playerStat in playerStats) {
for (s = 0; s < stats.length; s++) {
// if the player's statistic matches the id of the property from the stats object, we add that stat name and its total for that player as a property of the object we created above
if (playerStat === JSON.stringify(stats[s].id)) {
let statName = stats[s].name;
let statCount = playerStats[playerStat];
statistics[statName] = statCount;
}
}
};
// Now we turn our statistics object into text that can actually go into our table
let prettyStats = "";
for (statistic in statistics) {
prettyStats = prettyStats + `${statistic}: ${statistics[statistic]}
`
}
// Now that we have data for the player, we add a row to our table
$(tbl).append("<tr><td>" + id + "</td><td>" + team + "</td><td>" + pos + "</td><td>" + plyr + "</td><td>" + prettyStats + "</td>");
}
//Here's the bottom of our table and its creation inside the div
$(tbl).append("</tbody><br/><br/>");
$("#statOutput").append(tbl);
}
});
}
});
});
You'll probably want to do further text formatting on the output of prettyStats, but it gets you the data you're looking for.

How to access all nested associative array elements?

Situation : I receive JSON array from jQuery <-> PHP Ajax request. Here's structure of unparsed JSON aray :
{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
And after using JSON.parse(json); the structure looks like :
Focus: Object
brand: "Ford"
id: 2
name: "Focus"
Problem : I want to access all array's '1st tier' elements and use them like an object, but none of the following ways works :
for (var entity in dataTable)
{
formattedText += entity['brand'] + " " + entity['name'] + "<br>";
OR
formattedText += entity.brand + " " + entity.name + "<br>";
OR
formattedText += dataTable[0]['brand'] + " " + dataTable[0]['name'] + "<br>";
}
Any solutions how to read values of all object in this array?
The for..in loop uses keys and does not return the elements themself: for (var key in dataTable)You would then access each element with dataTable[key]. The key is actually the name of the Element.
You where using it as you would use a for..of loop, but that is a new feature not supported in all Browsers yet.
Demo:
var dataTable = {"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
var formattedText = ""
for (var key in dataTable)
{
formattedText += dataTable[key]['brand'] + " " + dataTable[key]['name'] + "<br>";
}
document.write(formattedText)
Object.keys will return array of all the keys of the object
You can loop(forEach/for-loop) through the keys to get the expected output.
Using forEach:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
keys.forEach(function(item) {
str += dataTable[item].brand + " " + dataTable[item].name;
});
alert(str);
Using for-loop:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
for (var i = 0, len = keys.length; i < len; i++) {
str += dataTable[keys[i]].brand + " " + dataTable[keys[i]].name;
}
alert(str);
The correct syntax to write this would be:
When you loop, you'll get the key name in the variable entity and then use that to get the value, also, you need to access the associative array inside the first key i.e. Focus
var dataTable = JSON.parse('{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}');
var formattedText = '';
for (var entity in dataTable.Focus) {
formattedText += dataTable.Focus['brand'] + " " + dataTable.Focus['name'] + "<br>";
}
Sounds like you're using each function in a wrong way. in your each function change arguments to key and value like this:
$.each(dataTable, function (key, value) {
//access key and values here
});
In your case u should iterate again over key and values of your key values.

javascript loop through json response

I want to loop through my json response. My json response looks like this
{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}
What I want is a foreach loop through all lines so i get the keys and the values for every line.
You could iterate like this: (added code-comments for explanation)
var result = document.getElementById("result");
var json = '{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}';
var obj = JSON.parse(json);
// json object contains two properties: "line" and "total".
// iterate "line" property (which is an array but that can be iterated)
for (var key in obj.line) {
// key here is the index of line array
result.innerHTML += "<br/>" + key + ": ";
// each element of line array is an object
// so we can iterate over its properties
for (var prop in obj.line[key]) {
// prop here is the property
// obj.line[key][prop] is the value at this index and for this prop
result.innerHTML += "<br/>" + prop + " = " + obj.line[key][prop];
}
}
// "total" is a property on the root object
result.innerHTML += "<br/><br/>Total = " + obj.total;
<p id="result"> </p>
Demo Fiddle: http://jsfiddle.net/abhitalks/ajgrLj0h/2/
.
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
for(var i = 0; i < json.line.length; i++)
{
console.log("Type: " + json.line[i].type + " Name: " + json.line[i].name + " Account: " + json.line[i].account + " Description: " + json.line[i].description + " Balance: " + json.line[i].balance + " Image: " + json.line[i].image);
}
You can do something like that...
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
if(json.line !== undefined && json.line.length > 0){
var key,value;
json.line.map(function(lineObject){
for (key in lineObject) {
value = (lineObject[key] == '')?'unknown': lineObject[key];
console.log(key+":"+ value);
}
console.log("---------------------");
});
}
http://jsfiddle.net/ddw7nx91/
var obj = {"line":[]} //your json here
for(var i=0; i<obj.line.length; i++) {
console.log(obj.line[i].type)
}
obj.line is an array, so you can get his length an cycle it.
This would create an array of lines each with a keys object and a values object.
var response = JSON.parse( {'your':'JSON'} );
var lines = [];
$.each( response, function( line ) {//loop through lines in response
var keys = [];
var values = [];
$.each( line, function( obj ) {
keys.push( Object.keys(obj) );//get keys
for( var key in obj ) {
values.push(obj[key]);//get values
}
});
lines.push({ {'keys':keys},{'values':values} });
});

How can iterate over JSON object and print its properties and their values?

I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`

Converting an array into JSON

I need to bring in a csv doc and convert it to JSON, so far I have been able to convert it to an array and from the array I'm trying to build a JSON object.
Below is the JavaScript that builds the JSON, but its not in the structure I need, underneath is an example of the structure required.
var jsonObj = []; //declare object
for (var i=1;i<csvAsArray.length;i++) {
jsonObj.push({key: csvAsArray[i][0]}); //key
for (var l=1;l<csvAsArray[0].length;l++) {
jsonObj.push({label: csvAsArray[0][l], values: csvAsArray[i][l]}); //label + value respectively
}
}
Final output required:
{
"key": "Sample 01",
"values": [
{
"label" : "Something" ,
"value" : 1
} ,
{
"label" : "Something" ,
"value" : 2
}
]
},
{
"key": "Sample 02",
"values": [
{
"label" : "Something" ,
"value" : 5
} ,
{
"label" : "Something" ,
"value" : 4
}
]
}
Simply use JSON.stringify() to convert your array to json string
var jsonString = JSON.stringify(yourArray);
You need to declare the values and push that onto a tmp variable before pushing that index onto the final/main object
var tmp_values, jsonObj = []; //declare object
for (var i=1;i<csvAsArray.length;i++) {
var tmp_values = [];
for (var l=1;l<csvAsArray[0].length;l++) {
tmp_values.push({label: csvAsArray[0][l], value: csvAsArray[i][l]}); //label + value respectively
}
jsonObj.push({key: csvAsArray[i][0], values: tmp_values}); //key
}
This script is a common way to convert an array to JSON in JavaScript.
I'm not a fan of answers like this, but this service in my opinion is good enough to warrant it. It can convert between various data formats including CSV, JSON, XML, HTML table, etc. It even offers variations in output structure for some of the formats.
http://shancarter.github.io/mr-data-converter/
use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}

Categories