访问JSON对象的元素不知道的键名 [英] Accessing elements of JSON object without knowing the key names

查看:936
本文介绍了访问JSON对象的元素不知道的键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的JSON:

  {D:{KEY1:值1
      KEY2:值2}}

是否有访问该数组中的键和值(在JavaScript)不知道什么键?

的任何方式

我的JSON的结构类似于这种情况的原因是,我正在通过jQuery调用的WebMethod返回一个字典。如果这是不可能与上面的工作,我需要改变什么约我返回数据的方式?

下面是我的webmethod的轮廓:

 <的WebMethod()GT; _
公共函数foo(BYVAL输入作为字符串)作为词典(字符串,字符串)
    昏暗的结果作为新词典(字符串,字符串)    code,做的东西    Results.Add(键,值)
    返回结果
结束功能


解决方案

您可以使用的for..in 结构通过你的对象的任意属性迭代:

 为(以obj.d VAR键){
    的console.log(键+键);
    的console.log(值:+ obj.d [关键]);
}

Here's my json:

{"d":{"key1":"value1",
      "key2":"value2"}}

Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?

The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?

Here's an outline of my webmethod:

<WebMethod()> _
Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)
    Dim Results As New Dictionary(Of String, String)

    'code that does stuff

    Results.Add(key,value)
    Return Results
End Function

解决方案

You can use the for..in construct to iterate through arbitrary properties of your object:

for (var key in obj.d) {
    console.log("Key: " + key);
    console.log("Value: " + obj.d[key]);
}

这篇关于访问JSON对象的元素不知道的键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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