簡體   English   中英

如何從JSON字符串中檢索多個屬性值

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

我有一個JSON字符串:

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

我想從中獲得某些價值。 我試過正則表達式:

到目前為止,我有

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

這很丑陋且效率低下,但是當我嘗試將它們結合時:

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

返回的結果是整個組,而不只是匹配的部分。

我想要a,b,c,d等於鍵的值,但我得到:

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

有沒有辦法在一行正則表達式中實現這一目標?

-UDPATE ----

我最終去了

  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我避免使用JSON.parse,因為我正在處理成千上萬的此類文件,並且由於只需要其中的一小部分,所以我不希望JSON.parse的速度過慢對服務器造成不必要的影響。

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

除非您輸入無效的JSON,否則該方法應該起作用。然后,您可能要考慮使用Regex,但即使如此,您可能仍要查看模板。

嘗試在一次調用.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