I am new to jQuery and Java script. I need to parse a JSON file that has arrays, I use this code:
$.getJSON('mat.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {'class': 'my-new-list', html: items.join('')}).appendTo('body');
});
For this JSON file:
{
"@file_name": "materials",
"materials": [{
"@site_name_English": "N/A",
"@site_name_Spanish": "N/A",
"@site_number": "1",
"zoom": [{
"@zoom_name_English": "Main Reservoir",
"@zoom_name_Spanish": "Depósito principal",
"@zoom_number": "1",
"icon": [
{
"@icon_name": "Info Icon 1",
"@icon_pin": "1"
},
{
"@icon_name": "Info Icon 2",
"@icon_pin": "2"
}
]
}]
}]
}
But my result is:
materials
[object Object]
How can I change my code so I will get the objects also when the loop meets them?
Rory McCrossan
338k41 gold badges322 silver badges353 bronze badges
asked Aug 8, 2013 at 8:01
Dim
4,87721 gold badges87 silver badges155 bronze badges
2 Answers 2
Use this:
$.each(data, function(key, val)
{
if(typeof val === 'object') {
$.each(val, function(keys, value)
{
items.push('<li id="' + keys + '">' + value + '</li>');
}
} else {
items.push('<li id="' + key + '">' + val + '</li>');
}
});
You need to check that value is object or not.
EDITED:
function checkObj(key, val, items){
if(typeof val === 'object') {
$.each(val, function(keys, value)
{
if(typeof value === 'object') {
checkObj(keys, value, items);
} else {
items.push('<li id="' + keys + '">' + value + '</li>');
}
});
}
}
And in the $.each function use this:
$.each(data, function(key, val)
{
if(typeof val === 'object') {
checkObj(key, val, items);
} else {
items.push('<li id="' + key + '">' + val + '</li>');
}
});
answered Aug 8, 2013 at 8:10
Code Lღver
15.6k16 gold badges61 silver badges75 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Code Lღver
@DanM you need to create a function that will be recursive function to read such JSON data. Give me time I will create that for you.
The program shows how to read json and store data into textbox
$(document).ready(function(){
$.getJSON("Test.json",function(data){
$.each(data,function(key,value){
alert(data[key].attrib1name);
alert(data[key].attrib2name);
$('input').val(data[key].enterpriseName);
activities=data[key].activities;
console.log(value);
});
});
});
Comments
lang-js
liid and content, respectively?