1

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).

Sri
  • 568
  • 1
  • 6
  • 18
  • 1
    *"However changing the data to '{"id":1234, "name"}' will work"*. No, it doesn't. – Gerardo Furtado May 06 '19 at 04:37
  • 2
    `{"id":1234, "name"}` is not valid either, you need a value `{"id":1234, "name":"somename"}` – mplungjan May 06 '19 at 04:39
  • 4
    Is the server supposed to be generating JSON? If so, don't you think it would be beneficial to update the server? – ctt May 06 '19 at 04:40
  • 1
    Your JSON code is invalid. You need to fix that, And in JSON the correct character is double quotes. Make the one who produced the invalid code fix it, – some May 06 '19 at 04:45
  • 1
    You need the server code to be fixed, because it probably have many more bugs. for example what happens if the string has a "single quote"? `{'test':'It doesn't work'}` – some May 06 '19 at 04:54

1 Answers1

0

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(")
BennyWood
  • 31
  • 4