admin管理员组

文章数量:1180476

How do I parse this json with jQuery?

DayEvents: [{
      "0": "886",
      "event_id": "886",
      "1": "5029",
      "user_id": "5029",
      "2": "Professional",
      "user_type": "Professional",
      ...

How do I parse this json with jQuery?

DayEvents: [{
      "0": "886",
      "event_id": "886",
      "1": "5029",
      "user_id": "5029",
      "2": "Professional",
      "user_type": "Professional",
      ...
Share Improve this question edited Jan 6, 2020 at 23:17 Mickael Lherminez 6951 gold badge11 silver badges30 bronze badges asked Jun 9, 2010 at 12:08 lolweblolweb 951 gold badge1 silver badge5 bronze badges 1
  • Why did you tag this with php ? – RobertPitt Commented Jun 9, 2010 at 12:22
Add a comment  | 

2 Answers 2

Reset to default 29

The term "parsing" is a bit misplaced since this is already in JSON format. You don't need to parse it, but just to access it. If it were a large String in JSON format then you indeed need to parse it into an useable JSON object first before accessing.

This JSON contains one property, the DayEvents, which in turn contains an array []. You can access properties using dot . operator. You can get an array item at the given index using [index] where zero 0 denotes the first item.

var json = { DayEvents : [{"0":"886","event_id":"886","1":"5029","user_id":"5029","2":"Professional","user_type":"Professional" }]};
var firstDayEvent = json.DayEvents[0];

The array in turn contains an object {}. Or maybe more than one? You can have more than one items in an array, you should then see [{}, {}, {}, ...] and you could then access each item in an loop like so:

for (var i = 0; i < json.DayEvents.length; i++) {
    var dayEvent = json.DayEvents[i];
    // ...
}

A single day event object has several properties: 0, event_id, 1, user_id, 2, etc. You cannot access properties starting with a number using dot . operator, you would then like to use the brace notation:

var zero = firstDayEvent['0'];
var eventId = firstDayEvent.event_id;
var one = firstDayEvent['1'];
var userId = firstDayEvent.user_id;
var two = firstDayEvent['2'];
// ...

alert(eventId); // 886
alert(two); // Professional

To learn more about JSON, check this tutorial.

Stolen from .parseJSON() doc.

Example:

Parse a JSON string.

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Your example code seems to be an object already. You would have the put braces around the whole thing to use and parse it with parseJSON.

本文标签: javascriptjquery json parsingStack Overflow