2016-03-01 66 views
1

多個屬性值有一個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的緩慢不必要地影響服務器。

+6

爲什麼你就不能使用'JSON.parse()來'並通過這樣做迭代找到值? – gurvinder372

+0

您的**問題標題** * JavaScript匹配提取多個值字符串* *與您實際要求的內容幾乎無關。你能改善嗎? –

+0

@ RokoC.Buljan我不確定如何正確地使用它,但對 – user6000875

回答

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

這應該工作,除非你有無效的JSON進來。然後你可能要考慮的正則表達式,但即使如此,你可能想看看模板。

0

使用RegExp/[[email protected]]+(?=",|"})/ig在單個呼叫嘗試.match()

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

+0

@ RokoC.Buljan查看更新的帖子。應該匹配OP – guest271314

+0

@ guest271314中所有對象屬性的值,您的答案與我所需要的非常接近,謝謝!不幸的是,你的函數會根據提供的數據的順序返回值,而且我不能真正知道哪個值是userId,電子郵件等,因爲數據不是來自我可以控制的東西。 – user6000875

+0

這是一個神祕的原因會建議用正則表達式解析JSON。 – 2016-03-02 03:04:22