如何应对json

时间:2015-12-05 22:21:38

标签: javascript arrays json facebook-graph-api

我被检索(响应)这样的对象

{
"data": [
{
  "name": "Let's go angular!",
  "start_time": "2015-12-05T11:30:00+0200",
  "id": "908575145894907"
},
{
  "name": "يوم دراسي: \"تقنيات البث الإذاعي و الفضائي\"",
  "start_time": "2015-10-21T10:00:00+0300",
  "id": "1640694736210572"
},
{
  "name": "الحفل الختامي لنشاطات النادي الهندسي",
  "start_time": "2015-10-20T11:00:00+0300",
  "id": "906776472735155"
},
{
  "name": "The challenge of handling Big Data",
  "start_time": "2015-03-17T09:30:00+0200",
  "id": "1489359784617992"
},
{

我怎么能用javascript处理这个?

2 个答案:

答案 0 :(得分:2)

您似乎收到了JSON string。如果它是一个字符串你应该解析它,否则按原样使用它。要解析它:

var object = JSON.parse(response);
// or do: var object = typeof response == 'string' ? JSON.parse(response) : response;

然后

var data = object.data; // which is a array

您可以通过其键获得所需内容......例如:

alert(data[0].name);
alert(data[1].name);

示例:http://jsfiddle.net/Sergio_fiddle/vabpko52/

答案 1 :(得分:0)

>>> class BinaryTree:
...     def __init__(self, content, leftSubtree=None, rightSubtree=None):
...         self.content = content
...         self.leftSubtree = leftSubtree
...         self.rightSubtree = rightSubtree
...     def __repr__(self):
...         return str(self.content)
...     def __iter__(self):
...         if self.rightSubtree:
...             for leaf in self.rightSubtree:
...                 yield leaf
...         yield self.content
...         if self.leftSubtree:
...             for leaf in self.leftSubtree:
...                 yield leaf
...
>>> Node = BinaryTree
>>> s = Node(1)
>>> t = Node(10, s, None)
>>> tree = BinaryTree(20, None, t)
>>> for x in (s, t, tree):
...     print(x)
...
1
10
20
>>> for node in tree:
...     print(node)
...
10
1
20

和@Sergio是正确的做法,这样做可以避免错误响应。

var json = {
"data": [ { "name": "Let's go angular!", "start_time": "2015-12-05T11:30:00+0200", "id": "908575145894907" }, { "name": "يوم دراسي: \"تقنيات البث الإذاعي و الفضائي\"", "start_time": "2015-10-21T10:00:00+0300", "id": "1640694736210572" }, { "name": "الحفل الختامي لنشاطات النادي الهندسي", "start_time": "2015-10-20T11:00:00+0300", "id": "906776472735155" }, { "name": "The challenge of handling Big Data", "start_time": "2015-03-17T09:30:00+0200", "id": "1489359784617992" }]};


for(i = 0; i < json.data.length; i++)
  {
    document.write("name: " + json.data[i].name + "<br>");
    document.write("start_time: " + json.data[i].start_time + "<br>");
    document.write("id: " + json.data[i].id + "<br><hr>");

  }