简体   繁体   中英

how to parse Json array in Javascript

I want to parse the json array given below.this is the json i get when inspect.

0: "Harpic Power Plus Original Liquid Toilet Cleaner" 1: "HARPIC Powerplus Disinfectant Toilet Cleaner, Original - 1L Liquid Toilet Cleaner"

but when i use json.parse() i get this error

ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at app.component.ts:42
at ZoneDelegate.invoke (zone-evergreen.js:364)
at Object.onInvoke (core.js:41938)
at ZoneDelegate.invoke (zone-evergreen.js:363)
at Zone.run (zone-evergreen.js:123)
at zone-evergreen.js:857
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:41916)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at resolvePromise (zone-evergreen.js:798)
at zone-evergreen.js:864
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:41916)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at drainMicroTaskQueue (zone-evergreen.js:569)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
at invokeTask (zone-evergreen.js:1621)
at XMLHttpRequest.globalZoneAwareCallback (zone-evergreen.js:1658)

Hold on, so initially you've done JSON.parse('{ "product_name": [ "Harpic Power Plus Original Liquid Toilet Cleaner", "HARPIC Powerplus Disinfectant Toilet Cleaner, Original - 1L Liquid Toilet Cleaner"]}'); and got an array? That's a JS array, not a JSON array. You can access its values using the array keys, eg const foo = JSON.parse('{ "product_name": [ "Harpic Power Plus Original Liquid Toilet Cleaner", "HARPIC Powerplus Disinfectant Toilet Cleaner, Original - 1L Liquid Toilet Cleaner"]}'); console.log(foo.product_name[0]); console.log(foo.product_name[1]); const foo = JSON.parse('{ "product_name": [ "Harpic Power Plus Original Liquid Toilet Cleaner", "HARPIC Powerplus Disinfectant Toilet Cleaner, Original - 1L Liquid Toilet Cleaner"]}'); console.log(foo.product_name[0]); console.log(foo.product_name[1]); hope this works

a json formatted of your sample would be like this:

 var myJson = { first: "Harpic Power Plus Original Liquid Toilet Cleaner", second: "HARPIC Powerplus Disinfectant Toilet Cleaner, Original - 1L Liquid Toilet Cleaner" }; console.log(JSON.stringify(myJson));

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