loop a recieved json string to get values by jquery - javascript

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

Related

Translate a html attribute to javascript object

$("div").click(function () {
var obj = { flammable: 'inflammable', duh: 'no duh' };
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
This works without problem and alerts key/value.
$("div").click(function () {
var obj = $(this).attr("obj");
$.each(obj, function (key, value) {
alert(key + ": " + value);
});
});
<div obj="{ flammable: 'inflammable', duh: 'no duh' }">click</div>
However this is not working?
change this line
var obj = $(this).attr("obj");
to
var obj = JSON.parse($(this).attr("obj"));
Also, you may want to use escaped double quotes rather than single quotes inside the object, make it
<div obj="{ \"flammable\": \"inflammable\", \"duh\": \"no duh\" }">click</div>
or
<div obj= '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}' >click</div>

Read json in JQuery

I have this file json where I have, for each event (when), some reaction (do):
{"title":"Building blocks",
"date":"'1452786221'",
"scenes":[
[{
"when":{"event":"init"},
"goto":""
},
{
"when":{"event":"e_dTou","position":"up"},
"do":[
{"action":"a_dME","position":"open"},
{"action":"a_dME","position":"close"}
],
"goto":""
}
]
]}
I read this json from the file manifest.json with an ajax call so the data returned is text already parsed.
url = "json/manifest.json";
$.ajax({
type: "POST",
url: url,
success: function(data) {
console.log(data.scenes.when);
},
error: function() {
alert("Call" + url + " failed...");
}
});
With my code on console I have undefined . I want to read every data of this json in JQuery and write it on console. How can I do it? Thank you in advance.
You can use $.getJSON
Example:
$.getJSON( "url/to/file.json", function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( key + ': ' + val );
});
console.log( 'items: ', items );
});
try like that:
$.getJSON( "ajax/test.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" );
});
I will give you some hint as my json is
{
$id: "1",
UserId: 1089,
Name: "abc",
Email: "xyz#web.com",
Password: "&*&*",
Phone: "9000000000",
Gender: "M",
AvatarName: "Jellyfish.jpg",
AvatarPath: "c:/folder",
CreatedAt: "2015-12-09T13:19:57.68",
ModifiedAt: "2016-01-11T15:16:25.297",
DOB: "05/06/1993"
}
and i fetched like that,
$(document).ready(function() {
$("#btn").on("click", function(a) {
var e = $("input#Email").val();
$.getJSON("http://192.168.0.1:24402/api/user/showbyemail?Email=" + e, function(a) {
$("input#Email").val(""), $("img#a").hide();
var e = a.AvatarPath;
$("#stage").html('<img id="a" src="'+ e + '" height="200" width="400">'),
$("img#a").hide(),
$("img#a").show(1e3),
$("#stage").append("<p> Name: " + a.Name + "</p>"),
$("#stage").append("<p>Phone : " + a.Phone + "</p>"),
$("#stage").append("<p> Gender: " + a.Gender + "</p>"),
$("#stage").append("<p> Email: " + a.Email + "</p>"),
$("#stage").append("<p> Password: " + a.Password + "</p>")
})
}), $(document).keypress(function(a) {
13 == a.which && $("#btn").click()
})
});
it may help you buddy
Ok, I have solved the problem. First I iterate three time the json and I put its content into trigger_json array.
$.each( data, function( key, val ) {
json.push(val);
});
$.each( json[2], function( key, val ) {
scenes.push(val);
});
$.each( scenes[0], function( key, val ) {
trigger_json.push(val);
});
Next to use the content of the array (when, do, goto, e..) I iterate trigger_json in this way:
for(i=0; i<trigger_json.length; i++)
{
// Use for example trigger_json[i].when.event
for(j=0; j<trigger_json[i].do.length; j++)
{
// Use for example trigger_json[i].do[j].action
}
}

How to get json value from response ajax?

My json response is like this :
http://imgur.com/WRfauG9
http://www.jsoneditoronline.org/?id=c4ded7d2934f62fb68a276cfb118d52e
I want display HotelNo, RmGrade, Meal and TotalRate
I try like this :
...
success: function (response) {
console.log(response);
$.each(response, function() {
$.each(this, function(k, v) {
// console.log(k);
// console.log(v);
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
});
}
...
But it's not working
How to get json value from response ajax correctly?
Any solution to solve my problem
Thank you very much
It would be easy to help you if you give us a sample of your JSON, but in the meantime, I suggest to loop on response.SearchAvailResponse.Hotel instead of response:
success: function (response) {
$.each(response.SearchAvailResponse.Hotel, function() {
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
}
Waiting for your JSON.
As I mentionned before, you will not have access to things like HotelNo by looping only through response. Here is a working solution:
`
for(i=0; i<response.SearchAvailResponse.Hotel.length; i++){
console.log(js.SearchAvailResponse.Hotel[i].HotelNo);
}
response.SearchAvailResponse.Hotel is an array of objects.
Assumption is that you are getting an array.
You dont have to have loop inside loop.
success: function (response) {
console.log(response);
$.each(response, function(index, v) {
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
}

How to list values in Jquery

I have a JSON data which is sent to getJSON method. JSON data is
[{"Name":"P1","Description":"D1","Attribute":"E,S","Value":"EV,SV"}]
and getJSON method
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
I would like to get the alert as
E : EV
S : SV
The code here is assuming you have the pair in order. The idea is split the attribute and value, then select the value with same index to alert.
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
var attrs = v.Attribute.split(",");
var values = v.Value.split(",");
for(var i = 0; i < attrs.length ; i++)
{
alert(attrs[i] + " : " + values[i]);
}
});
});
});
try this
$.getJSON(url, { Name: 'P1' }, function (data) {
var aSplit=data[0].Attribute.split(',');
var vSplit=data[0].Value.split(',');
alert(aSplit[0] + ' : ' + vSplit[0]);
alert(aSplit[1] + ' : ' + vSplit[1]);
});
If data is coming as string, then you need to eval(data) to get a javascript object.
Try :
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
data = eval('('+data+')');
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Categories