Parse Json Array in jQuery - javascript

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?

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>');
}
});

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);
});
});
});

Related

jQuery loop through JSON array

I have a json array which i fetch by a ajax call and would like to loop through it.
The array outputs a category titel and some data records within that category.
The array is as followed:
{"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]}
The basic each function like so can't help me.
$.each(data, function(key, value) {
console.log(value.title);
}
I want to be able to output it with the main category title and under that have the data records shown.
So for example i want it to look like this:
Travel (3 results):
Beautiful title 1
Beautiful title 2
Beautiful title 3
List item
Other (1 results):
Beautiful title 1
Any help would be greatly appreciated. Thank you.
var data = {"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]};
$.each(data, function (key, value) {
$('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
var list = $('<ul></ul>');
$('body').append(list);
$.each(value, function (index, titleObj) {
list.append('<li>' + titleObj.title + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
You would need nested .each() as the array contains nested objects.
$.each(data,function(i,object){
console.log(i +'('+object.length+')')
$.each(object, function (index, obj) {
console.log(obj.title);
});
});
Fiddle
Try
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
var data = {
"Travel": [{
"title": "Beautiful title 1"
}, {
"title": "Beautiful title 2"
}, {
"title": "Beautiful title 3"
}],
"Other": [{
"title": "Beautiful title 1"
}]
};
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Actually you have a Travel key their
So you can do it like :
$.each(data.Travel,function(key, value){
console.log(value.title);
}

jQuery JSON I continue to get [object Object] as a value

I was updating the script for my site to allow for API changes from v1 to v2 the changes being
V1
"ISteamClient": 0,
etc..
V2
"ISteamClient": {
"online": 1
},
etc..
But now when I write what val is for each of the parts I get [object Object] in return, so I found a guide in which I call val['online'] but I still get [object Object]. I haven't done much work with JSON, just simple first layer JSON (like V1)
function loadup() {
$.getJSON("https://steamgaug.es/api/v2", function(data) {
var items = [];
var ISteamClient = 2,
ISteamCommunity = 2,
ISteamGameCoorindator_440 = 2,
ISteamUser = 2,
IEconItems_440 = 2;
$.each(data, function(key, val) {
if (key === "ISteamClient") {
ISteamClient = val['online'];
console.log(key + " = " + val);
}
else if (key === "SteamCommunity") {
ISteamCommunity = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamGameCoorindator_440") {
ISteamGameCoorindator_440 = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamUser") {
ISteamUser = val['online'];
console.log(key + " = " + val);
}
else if (key === "IEconItems_440") {
IEconItems_440 = val['online'];
console.log(key + " = " + val);
}
});
//Sort and group data
});
}
What am I doing wrong?
You're logging val, which is an object.
I think you want to log val.online

JSON multi-value

i need help parsing the following:
{
"data": [
{
"Function": "Administration",
"SubFunction": "Facilities,Maintnce,Bldg Svcs,Other,Secretary"
},
{
"Function": "Communications",
"SubFunction": "Internal Communications,Marketing Comm,Other"
},
{
"Function": "Customer_Services",
"SubFunction": "Customer Engineer,Dispatcher,NonQuota Acct Supp Mgr,Other,PreSales-Network,Process and Systems,Quota Acct Supp Mgr,Remote Support Services,Rework,Service Offer Development,Services Logistics,Services Planning,Technology Consultant"
}
]
}
My jQuery code is:
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$.each(this.SubFunction, function(){
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
})
})
What should happen: The first option box should be filled with the "Function" and the second with the "SubFunction" upon the "Function" selection.
What is happening: The first option box does load up the "Function" values correctly, but the second drop down has all of the "Subfunction" from all "Function" with multiple instances of them.
Please help.
Thank You.
You need a change handler for this. This should do the job:
$select3 = $('#select3');
$select4 = $('#select4');
$.each(data.data, function() {
addOption($select3, this.Function);
});
$.each(data.data[0].SubFunction.split(','), function() {
addOption($select4, this);
});
$select3.on('change', function() {
$select4.html('');
$.each(data.data, function() {
if ($select3.val() === this.Function) {
$.each(this.SubFunction.split(','), function() {
addOption($select4, this);
});
}
});
});
function addOption($target, value) {
$target.append('<option id="' + value + '">' + value + '</option>');
}
http://jsfiddle.net/m88u76eL/
DEMO
Here is how to do it. You could use a data attribute to store the options for each function in the the option elements of select3, then when each of these options is selected, the value in the data attribute is read and parsed and used to populate select4 on-the-fly.
$select3.empty();
$.each(data.data, function(key, val){
$select3.append(
$('<option/>',{id:val.Function,text:val.Function,'data-sub-function':val.SubFunction})
);
});
$(function() {
$select3.on('change',function() {
$select4.empty();
$.each($('option:selected', this).data('sub-function').split(','), function(i,val){
$select4.append(
$('<option/>', {id:val,text:val})
);
});
})
.change();
});
You are already looping in data Object why are you doing a extra $.each ?
$select3.html('');
$select4.html('');
$.each(data.data, function(key, val){
$select3.append('<option id="' + val.Function + '">' + val.Function + '</option>');
$select4.append('<option id="' + val.SubFunction + '">' + val.SubFunction + '</option>');
});
This just work just find? Not tested tho just a quick post to help out

loop a recieved json string to get values by jquery

I'm trying to parse data returned from $.post().
[{"id":"1","text":"USD"},
{"id":"2","text":"CNY"},
{"id":"3","text":"PHP"},
{"id":"4","text":"AUD"},
{"id":"5","text":"SGD"},
{"id":"6","text":"JPY"}]
using this approach Jquery, looping over a json array
I did something like this:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$.each(data,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it gives me the error:
Uncaught TypeError: Cannot use 'in' operator to search for '120' in [{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]
I also tried:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$(data).each(function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it also gives me the error:
Uncaught Error: Syntax error, unrecognized expression: [{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]
How should I be doing this?
Your data comes in the form of array so you need to loop through each index and then fetch the values. So you can replace this :-
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
with :-
$.each( obj, function( key) {
console.log( obj[key].id + ':' + obj[key].text);
});
or you can do this :-
$.each( obj, function( key, value ) {
console.log( value.id + ':' + value.text);
});
key is the index of array. It will return 0,1,2..
I think the argument passed to your success callback function is of type string. Change it to:
function(data) {
var parsedData = JSON.parse(data);
$(this).html();
$.each(parsedData ,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
function(data) {
var value = JSON.parse(data);
$.each(value ,function(idx, obj) {
console.log("id : "+obj.id+" "+text:"+obj.text);
});
}
try this
$.post(base_url+'cgame/currency',{ gameID: gameID },
function(data) {
$(this).html(); //<-- becareful $(this) might not be the element you think it is
$.each(data,function(idx, obj) {
console.log( "id : " + obj.id);
console.log( "text: " + obj.text);
});
},'JSON');

getJSON not satisfied

I have 3 selects:
country, region, city
When choosing a country to be updated select the region on the country.
here's the code. like written logically. but the region is not updated
$(document).ready(function() {
$('select[name=ad_country]').change(function() {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', {country: current_country},
function(data) {
$('select[name=ad_region]').empty();
$.each(data.region, function(key, val) {
$('select[name=ad_region]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function(key, val) {
$('select[name=ad_city]').append('<option value="'+val.id_parent+'">'+val.name+'</option>');
});
});
}
);
}
you have an error on your clossing tags
You have missed the '}' at the end.Now try this Code :
$(document).ready(function () {
$('select[name=ad_country]').change(function () {
current_country = $(this).val();
$.getJSON('./core/AJAX/advertisement_changecountry.php', { country: current_country },
function (data) {
$('select[name=ad_region]').empty();
$.each(data.region, function (key, val) {
$('select[name=ad_region]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
$('select[name=ad_city]').empty();
$.each(data.city, function (key, val) {
$('select[name=ad_city]').append('<option value="' + val.id_parent + '">' + val.name + '</option>');
});
});
});
});

Categories