Iteration of JSON not working jQuery - javascript

I received a response from MY ajax as follows
"{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}"
After calling JSON.parse(result), the result looks like
{"analgesicTax":false, "unitPriceRequired":false, "toConsumer":true, "toRetailer":true, "taxName":"1"}
Up until that point everything seems to be ok. However, when I tried to print my key/value pairs by using following code
var data = JSON.parse(result);
console.log(data);
console.log(data.analgesicTax);
for (var prop in data) {
console.log(prop+"is" + data[prop]);
I tried both using with and without JSON.parse() but the output is same as follows.
0is{
1is"
2isa
3isn
4isa
5isl
6isg
7ise
8iss
9isi
10isc
11isT
12isa
13isx
14is"
15is:
16isf
17isa
18isl
19iss
20ise
21is,
22is"
23isu
24isn
25isi
26ist
27isP
28isr
29isi
30isc
31ise
32isR
33ise
34isq
35isu
36isi
37isr
38ise
39isd
40is"
41is:
42isf
43isa
44isl
45iss
46ise
47is,
48is"
49ist
50iso
51isC
52iso
53isn
54iss
55isu
56ism
57ise
58isr
59is"
60is:
61ist
62isr
63isu
64ise
65is,
66is"
67ist
68iso
69isR
70ise
71ist
72isa
73isi
74isl
75ise
76isr
77is"
78is:
79ist
80isr
81isu
82ise
83is,
84is"
85ist
86isa
87isx
88isN
89isa
90ism
91ise
92is"
93is:
94is"
95is1
96is"
97is}
It seems to me that rather than treat it like a JSON object, it is handling as a string array. Any Inputs?

If the result is already JSON, then you don't want to use JSON.parse() since JSON.parse() converts a string representation of JSON into an object. Simply run your for loop as you coded and you should be able to get all the keys and their values.
However, if you do start out with a string representation of a JSON object, that's when you want to use JSON.parse().
//Starting with a JSON object
var result = {
"analgesicTax": false,
"unitPriceRequired": false,
"toConsumer": true,
"toRetailer": true,
"taxName": "1"
}
for (var prop in result) {
console.log(prop + " is " + result[prop]);
}
console.log('');
//Starting with JSON represented as a string
var result = "{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}";
var data = JSON.parse(result);
for (var prop in data) {
console.log(prop + " is " + data[prop]);
}

try this.
var data = JSON.parse(result);
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});

Related

getJSON data add array item to variable

I am using this script to retrive JSON data from a file to my page.
$.getJSON('json/data.json', function(data) {
$('#getJSON-results').html(JSON.stringify(data));
});
<div id="getJSON-results"></div>
Right now it jsut displays all the data from JSON file as a string on the page.
How would I take the data from my JSON file and place each array into a variable? My data in the JSON file looks like this:
[{"target": "summarize(first, \"1d\", \"sum\")", "datapoints": [[38.393148148148143, 1423958400], [90.800555555555633, 1424044800], [159.06037037037032, 1424131200], [245.5933333333335, 1424217600], [126.94796296296299, 1424304000], [120.37111111111113, 1424390400], [103.04148148148151, 1424476800], [99.273796296296368, 1424563200], [89.38203703703708, 1424649600], [92.970462962963012, 1424736000], [105.62666666666664, 1424822400], [110.33962962962967, 1424908800], [118.54981481481482, 1424995200], [100.08018518518523, 1425081600], [92.52277777777779, 1425168000], [98.647619047618974, 1425254400], [94.585000000000008, 1425340800], [85.568796296296284, 1425427200], [157.82222222222222, 1425513600], [109.7596296296296, 1425600000], [112.53324074074077, 1425686400], [89.392592592592649, 1425772800], [97.253518518518518, 1425859200], [73.424629629629635, 1425945600], [92.377592592592578, 1426032000], [76.117870370370397, 1426118400], [77.83953703703699, 1426204800], [66.643518518518533, 1426291200], [63.748055555555531, 1426377600], [137.30018518518517, 1426464000], [53.480648148148134, 1426550400]]},
{"target": "summarize(second, \"1d\", \"sum\")", "datapoints": [[2.7291600529100535, 1423958400], [5.7797089947089892, 1424044800], [3.4261574074074059, 1424131200], [5.0516335978835958, 1424217600], [6.2272420634920582, 1424304000], [11.752605820105822, 1424390400], [7.8688624338624269, 1424476800], [5.7305555555555525, 1424563200], [5.2784391534391499, 1424649600], [6.4652380952380897, 1424736000], [4.7690277777777741, 1424822400], [4.1451587301587258, 1424908800], [8.4178902116402039, 1424995200], [4.7948611111111061, 1425081600], [4.8153835978835939, 1425168000], [5.3873148148148111, 1425254400], [7.2819378306878262, 1425340800], [5.2084391534391488, 1425427200], [8.098492063492051, 1425513600], [5.6563822751322697, 1425600000], [5.3091468253968195, 1425686400], [4.7850396825396793, 1425772800], [3.8716931216931179, 1425859200], [3.1934325396825369, 1425945600], [3.2083531746031722, 1426032000], [3.3434391534391512, 1426118400], [3.6162235449735438, 1426204800], [3.2094179894179891, 1426291200], [2.3699537037037026, 1426377600], [4.3973544973544945, 1426464000], [2.1901388888888893, 1426550400]]},
{"target": "summarize(third, \"1d\", \"sum\")", "datapoints": [[5.3710185185185182, 1423958400], [11.25367724867724, 1424044800], [8.2990079365079268, 1424131200], [8.710694444444437, 1424217600], [9.6381216931216898, 1424304000], [9.3845105820105807, 1424390400], [9.7305820105820047, 1424476800], [8.6268055555555474, 1424563200], [10.589166666666673, 1424649600], [10.235462962962957, 1424736000], [10.455892857142853, 1424822400], [14.282407407407405, 1424908800], [17.774404761904758, 1424995200], [18.154120370370364, 1425081600], [16.249543650793651, 1425168000], [15.29764550264551, 1425254400], [16.267671957671972, 1425340800], [20.121488095238096, 1425427200], [27.007685185185196, 1425513600], [17.577962962962971, 1425600000], [17.020873015873018, 1425686400], [14.627685185185191, 1425772800], [15.824821428571433, 1425859200], [11.837579365079364, 1425945600], [13.292539682539683, 1426032000], [12.064074074074073, 1426118400], [12.279457671957676, 1426204800], [9.3799074074073978, 1426291200], [7.8777314814814732, 1426377600], [13.161825396825407, 1426464000], [7.2587499999999956, 1426550400]]}]
I am new to using JSON and would also appreciate any advice on the approach I'm taking.
How can I now make this data accsessable outside the getJSON?
$.getJSON('json/data.json', function(data) {
yourData = data;
makeMeGlobal = yourData[0];
});
console.log(makeMeGlobal.datapoints);
Changing your function to the following will result in an object you can then reference normally:
$.getJSON('json/data.json', function(data) {
yourData = data;
});
You could then get the first set of datapoints like this:
yourData.datapoints[0]
Should be:
data.forEach(function (obj) {
// obj now has each JSON object in this array
var test = obj.target;
}
When you get a JSON from AJAX, it's already ready for use in the browser. This is one of the nice perks of using JSON over XML.
It's already an array, because the original JSON string was parsed by jQuery. If you use stringify, you will get a string which contains the JSON representing the array (not useful for your purposes, as it's the same string returned by the server).
For example:
$.getJSON('json/data.json', function(data) {
// Here, data is already an array.
var data_length = data.length;
for (var i = 0; i < data_length; i++) {
var obj = data[i]; // Here we have an object from the array
alert("I have an object which target is " + obj.target);
}
});
You need to iterate through json to retrieve the value you need and append the html.More infor # https://stackoverflow.com/a/18238241/909535 Something like this
`$.getJSON('json/data.json', function(data){
data.forEach(
function(val, index, array) {
//val.target will have target attribute's value
//val.datapoints is a array which you can iterate
}
);
}
);`

two json file in jquery one for taking data values and other for data types

I am trying to use two json file. One for taking the data type of data and other for getting the data value of data.
Since I don’t know how to use two json file in one so I stored one json values in a variable.
var data = {
“name”: “classxyz”,
“number”:”abc”,
Fields : [
{
“name”: ”studentname”,
“marks”:”int”
“doc”: “failed”
}
]
}
Second json file “student.json”
{
“datasvalue”:
[
{
“studentname”: “Jack”,
“marks”: “18”,
“place”: “newyork”
},
{
“studentname”: “sparrow”,
“marks”: “12”,
“place”: “london”
}
]
}
I want to take the value of data type from the first json and check it into the second json and then show the value of that data type which is taken in first json.
Example: From the first json I search name is “studentname” and now I want to print this “studentname” as a label and search it in the second json file (student.json) and print its value(sparrow) in front of studentname in textfield.
When I print the “marks” it should check from the first json file that it has “int” type and search its value from student.json value that is 18. If I try to put any other value it should not let me enter.
So far, I am able to do the following which is far away from what I have to do.
Can’t we use two json in one program? And why the .inArray is not working this way?
function ViewData()
{
function toArray(obj) {
var result = [];
for (var key2 in obj) {
var value = obj[key2];
result.push(key2);
if (typeof value === 'object') {
result.push(toArray(value));
} else {
result.push(value);
}
$('#stage').append('<p>'+ key2+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
}
return result;
}
var arra =[];
arra = JSON.strigify(toArray(data));
$('#stage1').html('<p>'+arra + "<br>"+'</p>');
//$('#stage1':contains('day'));
}
$.getJSON('student.json',
function(datas)
{
// Create an array to hold the data.
var items = [];
var storeName=[];
var storeValue=[];
// Parse the data by looking at each entry in the dates object.
$.each(datas.datasvalue,
function(key1, value1)
{
var i=0;
$.each(value1, function(key,value){
storeName[i]= key;
storeValue[i] = value;
$('#stage2').each(function(){
// if($.inArray(key.text(),arra)){
alert($.inArray(key,arra));
$(this).append('<p>'+ key+' : '+ "<input id=\"txtv\" type=\"text\" value=\""+value+"\"/>");
// }
}); // end of stage each funtion
i++;
}); // end of value and key funtion
}); // end of value1 function
}); // end of function (data)

how to browse a javascript object

I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});

How do I pass multiple JSON from servlet to Javascript

I want to pass 3 JSON to front end. I can pass all 3 individually. I did this to check if its working.
I do it this way:
response.getWriter().write(json.toString());
I read on one of the post on here that you could put the create a json array and send the array to the Ajax call.
So I tried doing this:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json.toString());
In the client side of the house:
$.ajax({
data: {param1: 'p1', param2: 'p2', param3: 'p3', param4: 'p'},
dataType: 'json',
url: './GetDataServlet',
type: 'POST',
success: function(data) {
var data1 = data[0];
var data2 = data[1];
var data3 = data[2];
$.each(data1 , function(i, val) {
$("#personal_data").append("<p> val.firstname </p>")
$("#personal_data").append("<p> val.lastname </p>")
)};
$.each(data2 , function(i, val) {
$("#department_data").append("<p> val.departmentid </p>")
$("#demartment_data").append("<p> val.departmentname </p>")
)};
//Not attaching the entire code, because it's quite long. :)
},
error: function() {
alert("An error occured while attempting fetch data.");
}
});
How can you pass multiple JSONs to the client side when you make an $.ajax call.
Thanks,
You could try sending a single array of the three objects. [Obj1 , Obj2 , Obj3]
If the three objects returned depend on the previous objects sent (say Obj2 depends on Obj1.X property is true or false you can have three separate calls
var firstResult = $.ajax({
url : firstUrl
... other details
});
var firstResult.done(function(Obj1){
if(Obj1.X){
$.ajax({
url : secondUrl
... other details
});
... other calls
});
In properly formed JSON and AJAX requests/responses, 1 call delivers 1 JSON string.
Of course, you can compose those JSON strings however you want within the allowable JSON structure. In your case, there is absolutely nothing wrong with composing three JSON objects within a JSON array wrapper.
I think perhaps your only issue is here:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json.toString());
The String json that you build is already a string, so you don't need to call toString() on it again. Just do:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json);
I was trying to do the same thing. I wanted to pass three json objects to my javascript. I tried making the three json objects into one json array and passing it,but it complicated the situation greatly.
I found that passing a string separated by a character I chose "%" is much easier.
String json1 = "....";
String json2 = "....";
String json3 = "...";
String toApp = json1 + "%" + json2 + "%" + json3;
Then in javascript you can split the text with
var split = line.split("%");
Finally a json object can be made from split[0], split[1] and split [2].
var c1= new Object();
c1.property1="test";
c1.property2="test";
var c2= new Object();
c2.property1="test";
c2.property2="test";
var data = { 'c1': c1, 'c2': c2 };
var parameters1 = JSON.stringify(data);
In ajax call pass parameters1 as data.
[WebMethod]
public static bool TestMethod(Object c1, Object c2)
{
}

How to pass an array of arrays into a function at JavaScript?

How can I define an array of arrays and pass that variable into a function so I can manipulate it at JavaScript?
As like:
JSP side:
object.method({ {"#id1",2}, {"#id2",3}...});
...
JS side:
var object= {
defaults: {
idSelector: "#id1"
},
method: function(options) {
if (options && !jQuery.isEmptyObject(options))
$.extend(this.defaults, options);
var that = this;
var opts = that.defaults;
//Try to reach every array step by step?
});
}
}
use json data format .
Convert your object into json string in your JSP page.
Parse that JSON string in your javascript.
Here's one of the ways to do that:
Your servlet can return a text, representing a json dictionary. Here's the documentation of a JSON API http://www.json.org/java/
Your javascript client code can fetch this json dictionary, something like:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
});
now items points to a bunch of <li> with your results
The functions' variable that will get the values should be like that(JSON format will be used):
defaults: [{
idSelector: '',
faqId: ''
}]

Categories

Resources