简体   繁体   中英

Parse json with special attribute in javascript

I have a json as below

"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"

There are two ways to access properties on an object:

  • obj.prop - dot notation
  • obj['prop'] - brackets notation

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:

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)” .

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)” .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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