7

I have this JSON :

var data =  [{
    "ID":1,"Name":"Test",
    "subitem": [
        {"idenID":1,"Code":"254630"},
        {"idenID":2,"Code":"4566"},
        {"idenID":3,"Code":"4566"}
    ]
}];

console.log(JSON.parse(data)); //Uncaught SyntaxError: Unexpected token o 

How to de-serialize data to javascript object.

Stephan Weinhold
  • 1,623
  • 1
  • 28
  • 37
titi
  • 1,025
  • 5
  • 16
  • 31
  • 3
    What you have here are [JavaScript literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Literals). Their syntax is precisely where JSON got its. But, within JavaScript code, JSON will always be formatted data stored within a `String`, which is the data type that `JSON.parse()` expects. – Jonathan Lonowski Sep 24 '13 at 02:53

2 Answers2

12

It already is an object ... of type Array. To access the Object:

var foo = data[0];

alert(foo.ID);

JSON.parse takes a String and parses it into an equivalent JavaScript value.

Alex
  • 34,899
  • 5
  • 77
  • 90
2

This is usable in Javascript. You need to parse JSON when your data is in String format and you get it from server side.

The purpose of JSON.parse is to convert to Javascipt Object Notation to use it. For example,

var str = "{"a":1,"b":2}";
var obj = JSON.parse(str); //obj = {a:1, b:2}

Reference MDN

Jhankar Mahbub
  • 9,746
  • 10
  • 49
  • 52
  • Technically, JSON.parse converts *from* JavaScript Object Notation to a native object. – Colin Brock Sep 24 '13 at 02:56
  • @Colin Can you explain little more. According to MDN, "Parse a string as JSON, optionally transforming the value produced by parsing." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – Jhankar Mahbub Sep 24 '13 at 03:02
  • 1
    @Khan: I think what he's saying is that `JSON.parse` parses a string containing JSON into a JavaScript object, and that only the former is called JSON, not the latter. – icktoofay Sep 24 '13 at 03:25
  • thank you @icktoofay Now it makes sense, JS object Notation in string is converted to JS object. (still a long way to learn English Language) – Jhankar Mahbub Sep 24 '13 at 03:29
  • @icktoofay: Thanks for clarifying :) I hope that's at least somewhat helpful, KhanSharp. – Colin Brock Sep 24 '13 at 04:17