简体   繁体   中英

Extract values from a JSON String

What's the best way to get a clean array from this:

[{f=[{v=2521998}, {v=0}, {v=99326}]}]

to something like this?

[2521998,0,99326]

Thanks!

As you haven't mentioned the [{f=[{v=2521998}, {v=0}, {v=99326}]}] is string or array , I've included both the answers.

For Array/Object/JSON

  1. Your json is not valid(See the correct formatted below)
  2. regex can be used in your case.

You can convert the object to string using JSON.stringify and then use regex to extract the required values from it.

 var myArr = [{ f: [{ v: 2521998 }, { v: 0 }, { v: 99326 }] }]; var str = JSON.stringify(myArr); var resultArr = str.match(/\\d+/g); alert(resultArr); 

String

If [{f=[{v=2521998}, {v=0}, {v=99326}]}] is string and not object/array , you don't need JSON.stringify .

 var str = '[{f=[{v=2521998}, {v=0}, {v=99326}]}]'; var resultArr = str.match(/\\d+/g); alert(resultArr); 

REGEX Explanation

  1. / : Delimiters of regex
  2. \\d : Matches any digit
  3. + : Matches one or more of the preceding class
  4. g : Global matches.

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