dongxian3852 2014-09-22 14:24
浏览 28
已采纳

从json [重复]获取特定信息

This question already has an answer here:

How can I get only "coords" data out of my json object in jquery? And for each object its own coords?

Example of returned json from php as shown in console:

[  
  {  
    "id":"7",
    "name":"EXAMPLE",
    "address":"example adress",
    "coords":"96.0,17.0"
  },
  {  
    same here etc.
  }
]

EDIT: Problem is I can't access json object in a way you all recommended. If I type object[0] I get "[" if I type object[1] I get "{" then I get all the other characters in a sequence '"', "i", "d", etc.

I do my console log in a sucessfull ajax call like so:

.done(function(data) {
    console.log(data[2]);
});

And my php returns data like so:

echo json_encode($myData);
</div>
  • 写回答

2条回答 默认 最新

  • dongzhi1822 2014-09-22 14:29
    关注

    Your data coming back is just a string, so you need to do one of 2 things to get it into JSON format:

    • in your .ajax call, set the option dataType: 'json' alongside the url, data etc parameters ( $.ajax({ url: 'x.php', dataType: 'json' ... }).done(function... )
    • manually parse the JSON in your .done() function ( .done(function(data) { data = $.parseJSON(data); ... }); )

    This will convert into it a JSON format, where my original answer below applied.


    Since your JSON is an array at the outermost level ([ ]), you can access the first-level items with array notation (eg. [0]). Inside that, you have an object ({ }) so you need dot-notation from there (eg. [0].coords).

    Assuming your variable is called myJson you can get at the first coords with myJson[0].coords, the second set with myJson[1].coords, etc. You can loop over myJson to get all coords in a loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持