简体   繁体   中英

Extract a value from json inside json string

var a = '{"test_cmd": "pybot  -args : {\"custom-suite-name\" : \"my-1556\"}}'
b = a.match("\"custom-suite-name\" : \"([a-zA-Z0-9_\"]+)\"")
console.log(b)

I have a json string inside json string.

I like to extract the property custom-suite-name 's value using the regex.

Output must be,

my-1556 .

But the return value b has no matches/null value.

Don't use a regexp to parse JSON, use JSON.parse .

var obj = JSON.parse(a);
var test_cmd = obj.test_cmd;
var args_json = test_cmd.replace('pybot  -args : ', '');
var args = JSON.parse(args_json);
var custom_suite = args.custom_suite_name;

It's better to put your regex within / slashes. NOte that,

  • There is a space exists before colon.
  • No need to escape double quotes.
  • Include - inside the character class because your value part contain hyphen also.

Code:

> a.match(/"custom-suite-name" : "([a-zA-Z0-9_-]+)"/)[1]
'my-1556'
> a.match(/"custom-suite-name"\s*:\s*"([a-zA-Z0-9_-]+)"/)[1]
'my-1556'

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