I have a JSON string:
x = '{"userId":"foo","traits":{"email":"[email protected]"},"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:
Wanted:
**>> ["foo","[email protected]","identify"]**
Actual results:
>> ["userId":"foo","email":"[email protected]","type":"identify"]
Is there any way to achieve this in one line regex?
--- 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.
JSON.parse()and find values by doing iteration?Javascript match extract multiple values stringin hardly related to what you're actually asking for. Can you improve?JSON.parse. You just need to access the relevant properties withobj.prop.JSON.parseis going to be slower than regexp; have you tested that? In fact, JSON parsers are usually quite fast. Anyway, if you have an "answer" to your own question, please add it as an answer, not as part of the question.