将嵌套数组字符串解析为数组

时间:2017-11-14 04:05:51

标签: javascript arrays json

我有一个示例嵌套数组字符串,如下所示:

const content = `[
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'paragraph',
    content: 'How do I remove a particular element from an array in JavaScript?',
  },
  {
    type: 'image',
    src: 'http://upload.sample.com/2016/0407/1460024231806.jpg',
    meta: {
      alt: 'Parse String to Float or Int',
      title: 'Parse String to Float or Int',
      caption: 'Parse String to Float or Int',
    },
  }
]`;

由于它是一个字符串,我使用JSON.parse()方法将其解析为一个数组,但它会抛出此错误:

VM926:3 Uncaught SyntaxError: Unexpected token t in JSON at position 10

有没有办法将这个字符串数组解析为数组?

1 个答案:

答案 0 :(得分:2)

Stringified JSON通常具有所有键的双引号。 还应该丢弃额外的逗号(,s),使其成为有效的json。

const content = `[
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "paragraph",
    "content": "How do I remove a particular element from an array in JavaScript?"
  },
  {
    "type": "image",
    "src": "http://upload.sample.com/2016/0407/1460024231806.jpg",
    "meta": {
      "alt": "Parse String to Float or Int",
      "title": "Parse String to Float or Int",
      "caption": "Parse String to Float or Int"
    }
  }
]`;