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.
Related
The array fetched has a key and value for each item but I want to get a simple index for each value ie 0, 1, 2, 3, 4 etc which currently is not what the key gives (and nor do I want it to). Using index also does not seem to work.
$.getJSON( "filepath/current.json", function(data) {
var items = [];
$.each( data, function(key,val) {
items.push( "<p id='" + key + "'>" + val + "</p>" );
});
});
For objects jQuery each doesn't support for an index parameter. But you can create an index for your own without any problems. ;)
var data = {
one: "ONE",
two: "TWO",
three: "THREE"
},
items = [];
//Use a simple counter ;)
(function() {
var i = 0;
$.each(data, function(key, val) {
items.push("<p id='" + i + "'>" + val + "</p>");
i++;
});
})();
console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => "<p id='" + index + "'>" + val + "</p>");
console.log(items);
And it even cleaner with ECMAScrpt6 template litteral:
var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => `<p id='${index}'>${val}</p>`);
console.log(items);
The key property is literally the index. If the key isn't a numeric index then your data is not an array but an object.
Your choices are:
a) rethink and redesign the solution. What are you going to use 0, 1, 2 etc for? Can it be replaced?
b) introduce a variable outside the each scope and manually increment it inside the scope. If you need to access the val later using the numeral index, you should map that data object to an array of objects containing only key and val properties.
$.getJSON( "filepath/current.json", function(data) {
var items = [];
for(key in data) {
var insert_key=parseInt(key)||0;
items.push( "<p id='" + insert_key + "'>" + data[key] + "</p>" );
}
});
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} });
});
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);
}`
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();
}
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>";
}