jquery - convert string to javascript object -
"{india=99, pakistan=30}"
i having string in form , want convert json object. have tried
json.parse({india=99, pakistan=30}).
but getting errors
vm2602:1 uncaught syntaxerror: unexpected token o in json @ position 1
there 2 issues string:
- keys , values separated colon(
:
) , not equals to(=
). - keys should wrapped in quotes.
though best way rectify json(input string) string itself, can try approach create object current string.
note: not robust solution. since solution relying on commas in string split, if pattern available in value
{india=100, 000, 000}
, solution fail. treat last resort. string manipulation never 100% covered.
var str = "{india=99, pakistan=30}"; var kv = str.substring(1, str.length -1); var list = kv.split(", "); var result = list.reduce(function(p,c){ var parts = c.split('='); p[parts[0]] = parts[1]; return p; }, {}) console.log(result)
Comments
Post a Comment