多個屬性值有一個JSON字符串:我如何從JSON字符串
x = '{"userId":"foo","traits":{"email":"[email protected]"},"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","[email protected]","identify"]**
Actual results:
>> ["userId":"foo","email":"[email protected]","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的緩慢不必要地影響服務器。
爲什麼你就不能使用'JSON.parse()來'並通過這樣做迭代找到值? – gurvinder372
您的**問題標題** * JavaScript匹配提取多個值字符串* *與您實際要求的內容幾乎無關。你能改善嗎? –
@ RokoC.Buljan我不確定如何正確地使用它,但對 – user6000875