【问题标题】:Uncaught SyntaxError: Unexpected number when trying to read json data未捕获的 SyntaxError:尝试读取 json 数据时出现意外数字
【发布时间】:2015-04-26 06:05:54
【问题描述】:

我像这样从谷歌地图 api 检索一个 json

$http.get("https://maps.googleapis.com/maps/api/geocode/json?address="+data.SimpleProfileForm.postcode+"&sensor=false")
                                    .success(function(data){
                                        console.log(data);
                                        user.location = data.results.0.address_components.3.long_name;
                                    })
                                    .error(function(data){
                                        console.log("there was an error with the postcode API");
                                        console.log(data);
                                    })

但我在这一行得到错误的意外数字:

user.location = data.results.0.address_components.3.long_name;

如果我删除我得到的数字'无法读取未定义的属性“long_name”'。

我如何访问数组中的数据?提前致谢, 克里斯

【问题讨论】:

  • 你能提供json响应吗?从这些信息中我们无法判断响应的结构
  • 如果是数组,则需要使用方括号表示法来访问其元素:user.location = data.results[0].address_components[3].long_name; 点表示法用于对象的非数字属性。

标签: javascript arrays json angularjs google-maps-api-3


【解决方案1】:

您不能使用点表示法对数组进行索引。

您的代码行应该是:

user.location = data.results[0].address_components[3].long_name;

【讨论】:

    【解决方案2】:

    在遍历 JSON 时,您不能直接引用 # 键。

    例如:getJSONitem = parent.221.grandchild.0

    要解决这个问题,您可以通过索引将键引用为字符串,因为 JSON 键都是字符串。

    例如:getJSONitem = parent['221'].grandchild['0']

    您没有将它们设为字符串,但我认为如果它们包含诸如“/-_”之类的随机字符......

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 2014-05-24
      相关资源
      最近更新 更多