简体   繁体   中英

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this

jsonData:   "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"

I can target the 'jsonData' object but that returns everything within the double quotes as a string. I tried...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.

Whats the easiest way to target the values only?

If you don't want to spend the time fixing your JSON just do this:

let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))

console.log(values)

If you want to interact with it like the list I would consider something like

var list = jsonData.split("[")[1].split("]")[0].split(",")

Console.log(list);

The console reads:

[
  '350.23', '250.32',
  '150.34', '340.50',
  '236.70', '370.45',
  '380.55'
]

From here you can use list[3] to get 340.50

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