简体   繁体   中英

Convert JSON String to JSON Object in JavaScript

I understand there are many similar questions exist, however I couldn't find a proper answer.

Consider the Javascript object,

var a = [ { defaultCount:'200' , timeintervals : [{ day:'Weekday', from:'9:00', to:'18:00', count:'100' }, { day:'Weekday', from:'9:00', to:'18:00', count:'100' } ]}];

Now running a[0].defaultCount gives me "200" as expected.

Now the same Javascript object, I am putting inside double quotes.

var b = "[ { defaultCount:'200' , timeintervals : [{ day:'Weekday', from:'9:00', to:'18:00', count:'100' }, { day:'Weekday', from:'9:00', to:'18:00', count:'100' } ]}]";

here b[0] gives me "[" and b[4] gives me "d" so on.

If I understand correctly, var a is JavaScript Object and var b is String. I am receiving var b from the Java side as a String. How do I convert var b into a form that I can iterate as I do on var a?

I have tried: var c = JSON.parse(b) but getting syntax error.

I really do not wish to change the JSON format much as it is the template used in the Java end as well. Are there any easy workarounds?

console screenshot

[{ 
  "defaultCount":"200" , 
  "timeintervals": [{ "day":"Weekday", "from":"9:00", "to":"18:00", "count":"100" }, { "day":"Weekday", "from":"9:00","to":"18:00", "count":"100"}]
}]

use double quotes

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