简体   繁体   English

从JSON检索值

[英]Retrieve values from a JSON

I want to extract the tenantId value from the below given json 我想从下面给定的json中提取tenantId值

{
  "ClientAccounts":{
   "@tenantId":"entpriseDemo",
   "clientAccount":[
    {
     "guid":"447a0bac-51e0-4f5f-b504-97dca5825530",
     "totalValueFormatted":"$1,100,000"
    }
   ]
  }
}

This is my javascript function for calling an ajax request and the success function code 这是我的javascript函数,用于调用ajax请求和成功函数代码

$.ajax({
      url: "$clientAccountsURL",
      cache: false,
      dataType: "json", // set to json or xml
      success: function(data){

        alert(data.ClientAccounts.tenantId);


    } 
});

When I'm alerting the value of tenantId in the success function it's returning me undefined value though i checked on the firebug its available in the json array. 当我在成功函数中警告tenantId的值时,尽管我检查了Firebug在json数组中可用的值,但它仍返回未定义的值。

Is there any another way to retrieve the value of tenantId. 还有其他方法可以检索tenantId的值。

Use the square brackets notation 使用方括号表示法

data.ClientAccounts['@tenantId']

From this mdn article : 这篇mdn文章

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. 对象属性名称可以是任何有效的JavaScript字符串,也可以是任何可以转换为字符串的内容,包括空字符串。 However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. 但是,任何不是有效JavaScript标识符的属性名称(例如,具有空格或连字符或以数字开头的属性名称)都只能使用方括号符号来访问。

您应该能够像关联数组一样使用它来访问它:

data.ClientAccounts['@tenantId']

Since the property name contains an @ you will have to access the property using the associative array syntax. 由于属性名称包含@您将必须使用关联数组语法访问属性。

data.ClientAccounts["@tenantId"];

JsFiddle: http://jsfiddle.net/VS9xe/ JsFiddle: http : //jsfiddle.net/VS9xe/

You can use either object notation or and associative array notation: 您可以使用对象符号或关联数组符号:

In your case, use associative array notation: 在您的情况下,请使用关联数组符号:

alert(data.ClientAccounts["@tenantId"]);

example: http://jsfiddle.net/2kdWQ/1/ 示例: http//jsfiddle.net/2kdWQ/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM