0

I am using JSOn in my javascript code. the javascript gets the following JSON message:

{"param1":1, "param2":{"aaa":1,"bbb":2,"ccc":3}, "param3":true}

In JavaScript I wrote the following code:

parsedArgs = JSON.parse(args);
alert(parsedArgs.param2);
parsedArgs.param2= JSON.parse(parsedArgs.param2);

in the alert I can see [Object object] but JSON.parse(parsedArgs.param2) fails with SyntaxError: invalidcharacter.

I want to get the inner parameters of param2 but JSON parser is not working. can you please help me? what is my problem?

thanks

3
  • 2
    aren't you missing quotes around param2? Commented May 27, 2013 at 8:38
  • JSON.parse() expects a JSON string, not an arbitrary JavaScript variable. See LightStyle's answer. Commented May 27, 2013 at 8:42
  • If the alert displays [Object object] then parsedArgs.param2 is already a parsed object. You dont ned to parse it again. Try alerting alert(parsedArgs.param2.aaa); and check the result Commented May 27, 2013 at 8:42

2 Answers 2

2

The problem is that you are parsing your JSON string too much time. JSON.parse is a recursive function which converts a string to a valid JS object using the JSON format. This means that once you have parsed it with the first JSON.parse you don't have to parse again object's properties, because they have already been parsed. You can access it directly doing parsedArgs.param2.aaa for example.

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

Comments

0

missing quotes in param2

{
    "param1": 1,
    "param2": {
        "aaa": 1,
        "bbb": 2,
        "ccc": 3
    },
    "param3": true
}

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.