javascript - How to retrieve multiple property values from JSON string -
i have json string:
x = '{"userid":"foo","traits":{"email":"foo@foobar.com"},"type":"identify"}'
that want values from. tried regex:
so far have
anonid = x.match(/\"anonymous_id\"\:(.*?)/)?[1] email = x.match(/\"email\"\:\"(.*?)\"/)?[1] userid = x.match(/\"userid\"\:\"(.*?)\"/)?[1] type = x.match(/\"type\"\:\"(.*?)\"/)?[1]
which ugly , inefficient, when attempt combine them:
[_, a, b, c, d] = x.match(/\"anonymous_id\"\:(.*?)|\"userid\"\:(.*?)|\"email\"\:(.*?)|\"type\"\:(.*?)/g)
the results returned entire group, instead of matched parts.
i want a,b,c,d equal value of keys, instead get:
wanted: **>> ["foo","foo@foobar.com","identify"]** actual results: >> ["userid":"foo","email":"foo@foobar.com","type":"identify"]
is there way achieve in 1 line regex?
--- udpate ----
i ended going
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 , need small piece of it, don't want slowness of json.parse impact servers unnecessarily.
try { var parsed = json.parse(x); anonid = parsed.anonymous_id; } catch (ex) { //invalid json }
that should work unless have invalid json coming in. , might want consider regex might want @ templates.
Comments
Post a Comment