【问题标题】:Parse JSON string inside of a object解析对象内部的 JSON 字符串
【发布时间】:2021-08-24 15:04:48
【问题描述】:

我正在尝试解析 JSON 对象内的 json 字符串,但继续收到“意外令牌”或“意外结束输入”错误。任何帮助将不胜感激!

语法如下:

{
  full_name: 'John Doe',
  company_name: 'TEST',
  sample: 't-e-s-t',
  populated: '{"type":"Select","manualTitle":"Manual Title","manualBody":"Email Message will go here","templateTitle":"Title Here","templateBody":"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old."}',
  messageBody: 'New body test'
}

【问题讨论】:

  • 你用来解析 JSON 的 JS 是什么样的?
  • 这是一个 JS 对象,不是 JSON 对象。 (populated 属性是 JSON)
  • JSON.parse(obj.populated)
  • @Kinglish OP 将他们的对象字面量称为“JSON 对象”(这是一个没有任何存在权的术语)。但是,是的,它工作正常:jsfiddle.net/2mqxr0kn

标签: javascript json parsing


【解决方案1】:

这是一个 JavaScript 对象,而不是 JSON。 (JSON is a string 并且有一个非常具体的语法。)所以使用JSON.parse 来解析对象的populated 属性的值,然后你可以提取它的键和值。

const obj = {
  full_name: 'John Doe',
  company_name: 'TEST',
  sample: 't-e-s-t',
  populated: '{"type":"Select","manualTitle":"Manual Title","manualBody":"Email Message will go here","templateTitle":"Title Here","templateBody":"Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old."}',
  messageBody: 'New body test'
};

const populated = JSON.parse(obj.populated);
console.log(populated.manualBody);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多