【问题标题】:Accessing an specific atribute pair in a json object访问 json 对象中的特定属性对
【发布时间】:2014-04-12 03:39:27
【问题描述】:

我需要访问温度并将其附加到我的页面如果这些都是对象,那么我想我不能使用索引,因为顺序无关紧要,这让我很失望。

{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
  "conditions": 1
 }
},
"current_observation": {
"image": {
  "url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
  "title": "Weather Underground",
  "link": "http://www.wunderground.com"
},
"display_location": {
  "full": "Toms River, NJ",
  "city": "Toms River"

},
"observation_location": {
  "full": "Stonehedge, Toms River, New Jersey",
  "city": "Stonehedge, Toms River",
  "state": "New Jersey",
  "country": "US"

},
"estimated": {},
"station_id": "KNJTOMSR5",
"observation_time": "Last Updated on April 11, 10:56 PM EDT",
"observation_time_rfc822": "Fri, 11 Apr 2014 22:56:39 -0400",
"observation_epoch": "1397271399",
"local_time_rfc822": "Fri, 11 Apr 2014 22:56:40 -0400",
"local_epoch": "1397271400",
"local_tz_short": "EDT",
"local_tz_long": "America/New_York",
"local_tz_offset": "-0400",
"weather": "Clear",
**"temperature_string": "59.6 F (15.3 C)"**

 }
}

我现在的 javascript 显然是这个,因为我还没有弄清楚如何访问这个项目

$(function() {
$("#getzip").submit(function() {
var zip_data =$(this).serialize();
    $.getJSON("get_weather.php",null, function(data); {

我需要将它附加到我的页面的 dom 中,我认为它应该看起来像这样?

   (#output).append(data.temperature_string);

【问题讨论】:

  • 您的 JSON 看起来不完整,但请尝试 zip_data.temperature_string。如果是数组,使用zip_data[i].temperature_string循环遍历数组
  • 我只使用了 json 的一部分,因为它是一个巨大的文件,如果有帮助,我只需要访问这个 temp 实例
  • 看看这个小提琴是否有帮助jsfiddle.net/mwr58/1/-看起来你可能想要<YOUR OBJECT>.current_observation.temperature_string
  • 这个数据中没有数组,只是一个相互嵌套的对象列表,我从顶部开始,只粘贴到我需要的值@Chase我会检查出来。其实链接已经失效了
  • @CoreyBuchillon - 它试图包含连字符:尝试 jsfiddle.net/mwr58/1/

标签: javascript php jquery json object


【解决方案1】:

将 json 对象导入 javascript。

这样使用。

在 PHP 中

 $json ='{"temperature":"36 c"}';

在 Javascript 中

$.post("get_weather.php",null, function(data){
 var temperature = data.temperature; // here you'll get temperature from json into variable
 console.log(temperature);
           },"json");

就是这样

【讨论】:

    【解决方案2】:

    console.log(data["temperature_string"]) 应该访问该数据。

    【讨论】:

    • 我应该更清楚,我需要访问它并将其附加到我页面的 DOM 所以如果我可以做类似 (#output).append(data["temperature_string"]) ;这将解决我的问题
    猜你喜欢
    • 2019-06-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2021-04-29
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多