简体   繁体   中英

How to access JSON element which has “-” character in the name in JavaScript

I have a JSON object which returns following values.

{
   "articles":[
      {
         "paper-id":"id",
         "paper-id-type":"type",
         "title":"title",
         "url":"url",
         "abstract":"abs",
         "date":"date",
         "publication-forum":"forum",
         "publication-forum-type":"type",
         "authors":"auth",
         "keywords":"key1,key2"
      }
   }

I tried to access these results through JavaScript. First I created an array and assigned these results to the array.

The content of the array (named articles) object looks like this;

abstract: "xxx"
authors: "yyy"
date: "1111"
keywords: "key1, key2"
paper-id: "abc"
paper-id-type: "xxx"
publication-forum: "yyy"
publication-forum-type: "zzz"
title: "www"
url: "url"

Then I tried to access each value in these elements using the format,

articles[0]["abstract"]

It works for elements that do not have "-" character. So when I tried to extract the paper-id;

articles[0]["paper-id"]

I'm getting the error [Exception: SyntaxError: Unexpected token []

Does anyone know how to solve this problem ?

The problem is because you forgot to close the [] and the {} in your JSON

You JSON should look like this

{
   "articles":[
      {
         "paper-id":"id",
         "paper-id-type":"type",
         "title":"title",
         "url":"url",
         "abstract":"abs",
         "date":"date",
         "publication-forum":"forum",
         "publication-forum-type":"type",
         "authors":"auth",
         "keywords":"key1,key2"
      }]
}
abc = {
    "articles": [{
            "paper-id": "id",
            "paper-id-type": "type",
            "title": "title",
            "url": "url",
            "abstract": "abs",
            "date": "date",
            "publication-forum": "forum",
            "publication-forum-type": "type",
            "authors": "auth",
            "keywords": "key1,key2"
        }
    ]
};

for (i in abc['articles'][0]) {
    console.log(abc['articles'][0][i]);
}

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