0

I use the following code and I got error,I want to get it as array of objects so what I miss here?

Uncaught SyntaxError: Unexpected token o

https://jsfiddle.net/z4oxsa1b/1/

 var json = {
  "prov": [
    {
      "save": {
        "pa": "sa",
        "func": "sa"

      },
      "delete": {
        "pa": "sof",
        "func": "delete"

      }
    }
  ]
}

 console.log("Test2");
 var jsonParse = JSON.parse(json);
  • 2
    That sample is valid JavaScript. So it doesn't need to be parsed. – Mouser Aug 05 '15 at 08:22
  • @icke, You have a point, but JavaScripts parser are forgiving gods. That won't throw an error. – Mouser Aug 05 '15 at 08:25
  • @icke - do you mean like this https://jsfiddle.net/z4oxsa1b/2/ , the error is still exist –  Aug 05 '15 at 08:25
  • No like this: https://jsfiddle.net/z4oxsa1b/3/ – Mouser Aug 05 '15 at 08:26
  • @AlBundy - you still have a javascript OBJECT, which is not a JSON string, so it wont parse – Jaromanda X Aug 05 '15 at 08:26
  • What I know is The JSON.parse() method parses a string as JSON not an object – Kiran Shinde Aug 05 '15 at 08:28
  • @AlBundy, please read into [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) and [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse), [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). There are a bunch of good explanations out there. The links are all to MDN. – Mouser Aug 05 '15 at 08:40

2 Answers2

2

The variable json is already a valid javascript object. You should only use JSON.parse() on a string to parse it into an object. For instance

var obj1 = {a: 1};
var obj2 = JSON.parse('{"a": 1}');
obj1 == obj2 // true
MarshallOfSound
  • 2,629
  • 1
  • 20
  • 26
-3
var json = {
  "prov": [
    {
      "save": {
        "pa": "sa",
        "func": "sa"

      },
      "delete": {
        "pa": "sof",
        "func": "delete"

      }
    }
  ]
}
alert(json);
alert(JSON.stringify(json));

 console.log("Test2");
 var jsonParse = JSON.parse(json);

Your josn var is a valid JSON object. As you can see using alert. You can directly use it. Only if in any case you have had a String in valid format of JSON, you would have been needed to parse it to JSON object.

https://jsfiddle.net/z4oxsa1b/6/

Rishi
  • 1,646
  • 2
  • 15
  • 34