简体   繁体   English

如何从JSON字符串中检索多个属性值

[英]How to retrieve multiple property values from JSON string

I have a JSON string: 我有一个JSON字符串:

x = '{"userId":"foo","traits":{"email":"foo@foobar.com"},"type":"identify"}'

that I want to get certain values from. 我想从中获得某些价值。 I tried regex: 我试过正则表达式:

So far I have 到目前为止,我有

anonId = x.match(/\"anonymous_id\"\:(.*?)/)?[1]
email = x.match(/\"email\"\:\"(.*?)\"/)?[1]
userId = x.match(/\"userId\"\:\"(.*?)\"/)?[1]
type = x.match(/\"type\"\:\"(.*?)\"/)?[1]

which is ugly and inefficient, but when I attempt to combine them: 这很丑陋且效率低下,但是当我尝试将它们结合时:

[_, a, b, c, d] = x.match(/\"anonymous_id\"\:(.*?)|\"userId\"\:(.*?)|\"email\"\:(.*?)|\"type\"\:(.*?)/g)

the results that are returned are the entire group, instead of just the matched parts. 返回的结果是整个组,而不只是匹配的部分。

I want a,b,c,d to equal the value of keys, but instead I get: 我想要a,b,c,d等于键的值,但我得到:

Wanted:
**>> ["foo","foo@foobar.com","identify"]**
Actual results:
>> ["userId":"foo","email":"foo@foobar.com","type":"identify"]

Is there any way to achieve this in one line regex? 有没有办法在一行正则表达式中实现这一目标?

--- UDPATE ---- -UDPATE ----

I ended up going with 我最终去了

  rxp = /\"user_id\"\:\"(.*?)\"|\"anonymous_id\"\:\"(.*?)\"|\"type\"\:\"(.*?)\"/g

  anonId = null
  userId = null
  type = null

  while (arr = rxp.exec(bdy)) isnt null
    userId = arr[1] if arr[1]
    anonId = arr[2] if arr[2]
    type = arr[3] if arr[3]

FWIW I'm avoiding using JSON.parse because I'm processing thousands of these and as I only need a small piece of it, I don't want the slowness of JSON.parse to impact the servers unnecessarily. FWIW我避免使用JSON.parse,因为我正在处理成千上万的此类文件,并且由于只需要其中的一小部分,所以我不希望JSON.parse的速度过慢对服务器造成不必要的影响。

try {
   var parsed = JSON.parse(x);
   anonId = parsed.anonymous_id;
} catch (ex) {
  //invalid json
}

That should work unless you have invalid JSON coming in. And then you might want to consider Regex but even then you might want to look at templates. 除非您输入无效的JSON,否则该方法应该起作用。然后,您可能要考虑使用Regex,但即使如此,您可能仍要查看模板。

Try using RegExp /[az@.]+(?=",|"})/ig at single call to .match() 尝试在一次调用.match()使用RegExp /[az@.]+(?=",|"})/ig

 var x = '{"userId":"foo","traits":{"email":"foo@foobar.com"},"type":"identify"}'; var res = x.match(/[az@.]+(?=",|"})/ig); console.log(res); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM