Ravi
Ravi

Reputation: 182

error in parsing json data in javascript

[
  [
    {
      "Id": 1234,
      "PersonId": 1,
      "Message": "hiii",
      "Image": "5_201309091104109.jpg",
      "Likes": 7,
      "Status": 1,
      "OtherId": 3,
      "Friends": 0
    }
  ],
  [
    {
      "Id": 201309091100159,
      "PersonId": 1,
      "Message": "heyyyyyyyy",
      "Image": "",
      "Likes": 2,
      "Status": 1,
      "OtherId": 3,
      "Friends": 3
    }
  ]
]

I am trying to parse this JSON data in javascript,but its giving an error "SyntaxError: JSON.parse: unexpected character" Tell me how to parse or access this json data and how to get numbers of records saved in JSON data.

I am running this on firefox ..Please help me to resolve this problem.Thanks in advance

Upvotes: 0

Views: 160

Answers (2)

nilgun
nilgun

Reputation: 10629

If your msg variable is already a Javascript object literal you can access properties in it directly like you said : msg[0][0].Id

If it is a string you can use JSON.parse() function to obtain a JS object: Parse JSON in JavaScript?

Fiddle: http://jsfiddle.net/nilgundag/EdWKv/1/

var msg1 = [
  [
    {
      "Id": 1234,
      "PersonId": 1,
      "Message": "hiii",
      "Image": "5_201309091104109.jpg",
      "Likes": 7,
      "Status": 1,
      "OtherId": 3,
      "Friends": 0
    }
  ],
  [
    {
      "Id": 201309091100159,
      "PersonId": 1,
      "Message": "heyyyyyyyy",
      "Image": "",
      "Likes": 2,
      "Status": 1,
      "OtherId": 3,
      "Friends": 3
    }
  ]
];
$("#first").text(msg1[0][0].Id);

var myJSONString = '[[{"Id": 1234,"PersonId": 1,"Message": "hiii","Image": "5_201309091104109.jpg","Likes": 7,  "Status": 1,     "OtherId": 3,      "Friends": 0    }  ],  [    {      "Id": 201309091100159,      "PersonId": 1,      "Message": "heyyyyyyyy",      "Image": "",      "Likes": 2,      "Status": 1,      "OtherId": 3,      "Friends": 3    }  ]]';
var msg2 = JSON.parse(myJSONString);
$("#second").text(msg2[0][0].Id);

Upvotes: 2

Clover Wu
Clover Wu

Reputation: 29

I thought that the json str is valid。but when that string isn't in JS enviroment..that's format is invalid.

Upvotes: 0

Related Questions