简体   繁体   English

如何访问JavaScript名称中带有“-”字符的JSON元素

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

I have a JSON object which returns following values. 我有一个JSON对象,它返回以下值。

{
   "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. 我试图通过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; 因此,当我尝试提取纸张ID时;

articles[0]["paper-id"]

I'm getting the error [Exception: SyntaxError: Unexpected token [] 我收到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 问题是因为您忘记关闭JSON中的[]{}

You JSON should look like this 您的JSON应该看起来像这样

{
   "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]);
}

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

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