从JSON对象读取值 [英] Read values from JSON object

查看:89
本文介绍了从JSON对象读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试从JSON对象获取内容. 我一直在Google各处查找内容,由于某些原因,我认为应该起作用的内容不起作用.

I am currently trying to get contents from a JSON object. I've been looking all over google and what I think should work, for some reason, does not.

JSON看起来像这样:

The JSON looks something like this:

{"locatie0":{"naam0":["Domplein"],"value0":["value1"]},"locatie1":{"naam1":["Neude"],"value1":["value1"]},"locatie2":{"naam2":["Vredenburg"],"value2":["value1"]},"locatie3":{"naam3":["Stadhuisbrug"],"value3":["value1"]},"locatie4":{"naam4":["Korte Minrebroederstraat"],"value4":["value1"]}}

我使用下面的代码读取文件,但由于某种原因,它将始终返回未定义或NaN.

I use below code to read the file but for some reason it will always return undefined or NaN.

$.ajax({
    url: "_data/pleinen.json",
    type: 'get', 
    dataType: "json", 
    success: function(data) {
        for(var k = 0; k < _loc.length; k += 1) {
            var _locaties = data.locatie[k].naam[k];
            // Should alert "Domplein", "Neude", "Vredenburg", "Stadhuisbrug", "Korte Minrebroekstraat", 
            alert(_locaties);
        }
    }
});

有人可以查看我是否在代码中犯了任何错误,或者是否有更好的读取值的方法?

Can anybody see if i've made any mistakes in my code or if there's a better way to read the values?

推荐答案

locatie[k]尝试访问locatie中对象的属性k,但是在您的情况下,数字本身就是名称的一部分.您必须动态构建属性名称.此外,嵌套对象的每个属性都是一个带有一个元素的数组,因此您必须访问第一个元素:

locatie[k] tries to access the property k of the object in locatie, but in your case, the number is part of the name itself. You have to build the property name dynamically. In addition, each property of the nested objects is an array with one element, so you have to access the first element:

var _locaties = data['locatie' + k]['naam' + k][0];

您的数据结构有些奇怪.属性名称中的数字使访问数据更加困难.如果可以更改它,请将其更改为对象数组,如果不需要,则不要对属性使用数组:

Your data structure is a bit strange though. The numbers in the property names makes accessing the data more difficult. If you can change it, change it to an array of objects and don't use arrays for the properties if you don't need them:

[{"naam": "Domplein", "value": "value1"}, {"naam": "Neude", "value":"value1"}]

然后简单地访问数据:

for (var i = 0, l = data.length; i < l; i++) {
    var _locaties = data[i].naam;
}

这篇关于从JSON对象读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆