简体   繁体   English

在javascript中解析具有特殊属性的json

[英]Parse json with special attribute in javascript

I have a json as below 我有一个JSON如下

"facet_counts": {
     "facet_pivot": {
      "title,host,content,anchor,id": [
        {
          "field": "title",
          "value": "biglobe",
          "count": 192
        }
      ]
}}

As normaly I will parse it like: 通常,我将解析如下:

var json = JSON.parse(xhr.responseText);
var field = json.facet_counts.facet_pivot.title,host,content,anchor,id[0].field;

But this is wrong. 但这是错误的。

Can you tell me how to parse attribute "title,host,content,anchor,id" 您能告诉我如何解析属性“标题,主机,内容,锚点,id”

There are two ways to access properties on an object: 有两种方法可以访问对象的属性:

  • obj.prop - dot notation obj.prop点表示法
  • obj['prop'] - brackets notation obj['prop'] -方括号表示法

When the JS interpretor gets confused by some parts of a property name ( , in your case), you can use the brackets notation to access the property: 当JS解释器与属性名称的某些部分( ,在您的情况下)混淆时,可以使用方括号表示法访问该属性:

var json = JSON.parse(xhr.responseText); 
var field = json.facet_counts.facet_pivot['title,host,content,anchor,id'][0].field;

This answer summarizes quite well the identifier naming restrictions: 这个答案很好地总结了标识符命名限制:

An identifier must start with $ , _ , or any character in the Unicode categories “Uppercase letter (Lu)” , “Lowercase letter (Ll)” , “Titlecase letter (Lt)” , “Modifier letter (Lm)” , “Other letter (Lo)” , or “Letter number (Nl)” . 标识符必须以$_或Unicode类别中的“大写字母(Lu)”“小写字母(Ll)”“小写字母(Lt)”“修饰符(Lm)”“其他 ”开头 字母(Lo)”“字母数字(Nl)”

The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)” , “Spacing combining mark (Mc)” , “Decimal digit number (Nd)” , or “Connector punctuation (Pc)” . 字符串的其余部分可以包含相同的字符,以及任何U + 200C零宽度非连接符, U + 200D零宽度连接符以及Unicode类别“非间距标记(Mn)”“间距合并 中的字符标记(Mc)”“小数位数(Nd)”“连接器标点(Pc)”

A property can have any string as name, and in cases where the string does not match the description above, the property can only be accessed with the brackets notation. 属性可以使用任何字符串作为名称,并且在字符串与上面的描述不匹配的情况下, 只能使用方括号表示法访问该属性。 If the string does match the description, the brackets notation and the dot notation can be used interchangeably, though usually the dot notation is preferred due to it being less verbose. 如果字符串确实与描述匹配,则括号符号和点符号可以互换使用,尽管通常首选点符号,因为它不太冗长。

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

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