【问题标题】:Can't get Data from json object无法从 json 对象获取数据
【发布时间】:2017-08-15 07:10:09
【问题描述】:

我有这个脚本:

<script type="text/javascript">
        function requestimg(username){
                $.ajax({
                    url: '{% url "image" %}',
                    data: {
                      'username': username
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data) {
                            //Printing the whole data
                            console.log(data);
                            //Printing to see where I am
                            console.log("Name: ");
                            //Trying to rint the name
                            console.log(data[0].nombre);
                        }else {
                             alert("May Day");
                        }
                    }
                });
        }

我在读取 json 对象中的属性时遇到问题 当我打印数据时,我得到了这个:

{
    json: "[
        {
            "model": "polls.imagen",
            "pk": 17,
            "fields": {
                "n…"36",
                "imagen": "polls/static/pictures/dr.jpg"
            }
        }
    ]"
}

当我在我得到的代码上打印数据时:

Uncaught TypeError: Cannot read property 'nombre' of undefined

我试过像data.nombre 一样写它,但我只是得到undefined

我也试过这个console.log(data[0].fields);data[0].modeldata.model

重要我想澄清一下,我不知道为什么有 2 个 json 对象我应该只得到一个,即使我尝试放一个 [1] 而不是我得到的 [0]同样的错误。

我尝试了一些以前类似问题的答案,但没有帮助。

【问题讨论】:

  • 从技术上讲,您应该能够使用data[1].fields.nombre 访问nombre 字段(它似乎是数组中的第二项,所以data[1] 不是data[0]
  • @donnikitos 我试过了,它说 Uncaught TypeError: Cannot read property 'fields' of undefined
  • @JoseRamon 我刚刚展开了你的回复,试试data[0].json[0].fields.nombre 应该可以这样做
  • @donnikitos Uncaught TypeError: Cannot read property 'json' of undefined,我用data[0]data[1]data[n].json[n]尝试过

标签: javascript json ajax django


【解决方案1】:

您将能够访问每个字段

data.json[0].fields

你的 url 的响应是一个数组,名为 json

另外data.json 正在返回一个字符串,因此将其转换为 JSON

data.json = JSON.parse(data.json);

【讨论】:

  • 好吧,如果我使用它说undefined,但由于我有了新线索,如果我使用data.json[0],它会返回我[,我猜这是因为它把它当作一个字符串,如果我输入data.json[3],我会从model得到m
  • @JoseRamon 然后您可以使用 JSON.parse(data.json) 将其转换为正确的 json
  • 最后,非常感谢
  • @JoseRamon 或设置为jQuery.ajax({dataType: 'json'})
  • 是的@JoseRamon 将其转换为 JSON 首先执行此操作JSON.parse(data.json)
【解决方案2】:

先将其转换为 JSON JSON.parse(data.json)

这将使您可以访问字段对象data.json[0].fields

【讨论】:

  • 阅读我对 donnikitos 的重播,如果我使用它,我仍然会遇到问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-02
  • 2015-08-14
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多