I am experiencing a very strange behavior of Javascript.

I get the data object in the form of a string from the server as shown below,

"{'id':1234, 'name'}"

When I try to parse this data using JSON.parse() it throws

JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

However changing the data to '{"id":1234, "name"}' will work.

But my question is how do I transform:

"{'id':1234, 'name'}" to '{"id":1234, "name"}' 

in the javascript end? (I dont want to change any thing in the server).

1 Answers

0
Community On

Simply you need to replace the character(') as global, here the code:

var yourString = "{'id':1234, 'name'}";
yourString = yourString.replace(/\'/g, '"');
console.log(yourString);

And in vice versa:

var yourString = '"{\'id\':1234, \'name\'}"';
    yourString = yourString.replace(/\'/g, '"');
    yourString = yourString.replace(/\"/g, "'");
    console.log(yourString);

Here other example with mixed characters( " and ' ):

    var yourString = "{\"id':1234, 'name'}";
    yourString = yourString.replace(/\'/g, '"');
    console.log(yourString); // Automatically skips the right character(")