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:

  1. keys , values separated colon(:) , not equals to(=).
  2. 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

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -