简体   繁体   中英

Iteration of JSON not working jQuery

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM