1

From a GET request to a service I receive a JSON object like this:

{
  "id": "SWKJHFDJHSDFLSVNDHLSDKJHNLSDLSDNVLKVSNLK",
  "payload": "{ att1: value1, att2: value2}"
}

When it should be like this:

{
  "id": "SWKJHFDJHSDFLSVNDHLSDKJHNLSDLSDNVLKVSNLK",
  "payload": { "att1": "value1", "att2": "value2"}
}

The problem is that the payload has a bad format for a JSON object, and I can't transform it into a real object with JSON.parse().

How can I transform "{ att1: value1, att2: value2}" into a real JavaScript object?

4
  • is the format always the same? i.e. could a regex find/replace work for you? Commented Jul 3, 2015 at 14:03
  • @atmd yes, the format is always the same, is a regular object of two attributes but inside quotes like a string "{ a: a1, b: b1 }" Commented Jul 3, 2015 at 14:06
  • a better question to ask is why your JSON is coming back like that in the first place... Commented Jul 3, 2015 at 14:19
  • @Mike its a bug in the service that the creators say they are too busy to fix right now. Commented Jul 3, 2015 at 14:30

1 Answer 1

1

if the format is the same then you can use regex to insert the speach marks like this:

"{ att1: value1, att2: value2}".replace(/([a-z0-9]+)/g,"'$1'");

This will insert ' around the key and values in the string.

so: "{ att1: value1, att2: value2}".replace(/([a-z0-9]+)/g,"\"$1\"");

N.B. You'll have to account for the possibility of single and/or double speach marks in the values of your input/api/json response. gives "{ "att1": "value1", "att2": "value2"}"

the quotes must be double quotes " for json parse to work, so using json parse on the above will give you your object, in one line it's

var myObject = JSON.parse("{ att1: value1, att2: value2}".replace(/([a-z0-9]+)/g,"\"$1\""));
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't work, it's still a string, not and object, and cannot be transformed into an object with JSON.parse().
It worked! First time in my life that a regex solves a problem instead of creating them.
glad I could help. sorry I didnt spot the double quote mistake earlyer, always forget json requires double quotes over single

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.