Marco Greselin
Marco Greselin

Reputation: 21

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!

Upvotes: 0

Views: 100

Answers (1)

Tushar
Tushar

Reputation: 87233

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.

Upvotes: 5

Related Questions