6

I want to parse a JSON Object that contains some value as a json string, note that I don't know those fields previously, so I can't do something like obj[key]=JSON.parse(obj[key]). I am looking for an easy way to do that,

obj={
  Name:"{\"FirstName\":\"Douglas\",\"LastName\":\"Crockford\"}"
}

And I want to get

{
  Name:{
      FirstName:"Douglas",
      LastName:"Crockford"
      }
}
0

7 Answers 7

1

If you want to get paradoxical about it, you can handle arbitrarily nested versions of this scenario using the "reviver parameter". Start by stringifying your object!

function parseJSON(k,v) {
  try { return JSON.parse(v, parseJSON); }
  catch(e) { return v; }
}
JSON.parse(JSON.stringify(obj), parseJSON);

Is that nifty, or is it just me?

Sign up to request clarification or add additional context in comments.

Comments

0

We'll write a handy little utility which maps a function over object properties:

function mapObject(obj, fn) {
  const result = {};
  for (const prop in obj) result[prop] = fn(obj[prop], prop);
  return result;
}

Now you can create an object with all the JSON values in the input parsed by just saying

mapObject(obj, JSON.parse)

If you want to guard against property values which are not valid JSON, then

function parseJSON(x) {
  try { return JSON.parse(x); }
  catch (e) { return x; }
}

and then

mapObject(obj, parseJSON)

Comments

0

You could use Object.keys(obj) to get the property names to allow you to use JSON.parse()

2 Comments

Yeah thanks, I thought that i could have more pretty solution but I see that this is what I can do
and I must use try and catch , in case some value are not in json format
0

You can always try/pass on every key:

a = {
  a: 1,
  b: JSON.stringify({a: 1, b: 2}),
  c: 'asdf'
}
console.log(a);
new_a = {}
Object.keys(a).map((key) => {
  try {
    new_a[key] = JSON.parse(a[key]);
  } catch(err) {
    new_a[key] = a[key];
  }
})

console.log(new_a);

2 Comments

Purists would say that this is a misuse of map, and should be forEach. Their logic would be that map is designed for transforming one array into another, and should not be used for its side-effects, such as mutating the input.
I will do that with foreach , it's more convenient
0

You can simply loop over all the keys:

obj={
  Name: "{\"FisrtName\":\"Douglas\",\"LastName\":\"Crockford\"}",
  Other: "This isn't JSON"
};
for (var key in obj) {
    try {
        obj[key] = JSON.parse(obj[key]);
    } catch(err) {
        // ignore error, just leave it alone
    }
}
console.log(obj);

7 Comments

There will be a problem in case some of the values are not valid json strings
I thought all the values were JSON, didn't see "some" in the question.
From the question; "note that I don't know those fields previously, so I can't do something like obj[key]=JSON.parse(obj[key])"
Like I said, I didn't notice that. I've updated the answer.
@Dekel I use for, you use map.
|
0

I have succeeded with : jsonData['key']['value']

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

If you have nested JSON.parse statements and need to have a nested JSON string, the inner string needs 3 backslashes to escape the double quote.

For example if this was the entry point of your application:

(async () => {
  const event = JSON.parse(
    JSON.parse(process.argv.slice(2)[0]).Message,
  ) as MyEvent;

  processEvent(event);
})();

You would want to call this with a JSON string that looks something like this:

PS C:\_projects\eventProcessor> node dist\eventProcessor.js '{\"Message\":\"{\\\"myAttribute1\\\": \\\"myValue1\\\", \\\"myAttribute2\\\": \\\"myValue2\\\"}\" }'

Note that in windows the JSON string starts and ends with a single quote and has double quotes around the attributes and values within the object. Also, the inner string (i.e. Message object) needs to have the double quotes escaped with three (3) backslashes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.