"{INDIA=99, PAKISTAN=30}"
i am having string in this form , want to convert into json object. Have tried
JSON.parse({INDIA=99, PAKISTAN=30}).
but getting errors
VM2602:1 Uncaught SyntaxError: Unexpected token O in JSON at position 1
"{INDIA=99, PAKISTAN=30}"
i am having string in this form , want to convert into json object. Have tried
JSON.parse({INDIA=99, PAKISTAN=30}).
but getting errors
VM2602:1 Uncaught SyntaxError: Unexpected token O in JSON at position 1
There are 2 issues with your string:
:) and not by equals to(=).Though the best way would be to rectify the JSON(input string) string itself, you can try this approach to create an object from current string.
Note: This is not a robust solution. Since this solution is relying on commas in string to split, if this pattern is available in a value like
{India=100, 000, 000}, this solution will fail. So treat this as your last resort. String manipulation will never be 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)
Your input isn't valid JSON. You can try to transform it into an appropriate string and then call JSON.parse as you tried. See snippet below and feel free to ask if you have any further questions.
const str = "{INDIA=99, PAKISTAN=30}";
const result = JSON.parse(str.replace(/\=/g, ':').replace(/([a-zA-Z]+)/g, '"$1"'));
console.log(result);
console.log(result['INDIA']);
You need to have characters around the key, otherwise it won't read. So:
var str = '{"INDIA":99, "PAKISTAN":30}'
JSON.parse(str);
That should work.