【问题标题】:Parse nested object in JSON string解析 JSON 字符串中的嵌套对象
【发布时间】:2022-01-08 00:53:36
【问题描述】:

我有这个代码:

let test = '{"attribute_as":"plan_id","operator":"fromTo","values":"{"from":"70","to":"80"}"}';
console.log(JSON.parse(test));

它当然会失败,因为在values 我有一个对象。有什么选择如何以简单的方式解析这个字符串?还是根本不可能?

最后的结果应该是:

{
    attribute_as: 'plan_id',
    operator: 'fromTo',
    values: {
        from: 70,
        to: 80
    }
}

【问题讨论】:

  • 试试这个json字符串:'{"attribute_as":"plan_id","operator":"fromTo","values":{"from":70,"to":80}}'我认为错误只是一个放错了引号
  • 你的键值有错误,它的字符串不是一个对象,如果你想要一个字符串,你必须转义 " 内部值,或者你推迟拥有一个对象
  • 你从哪里得到字符串?如果它来自您可以控制的来源,最简单的方法是将字符串修复为真正的 JSON。

标签: javascript json string parsing


【解决方案1】:

字符串不正确:

let err = '{"attribute_as":"plan_id","operator":"fromTo","values":"{"from":"70","to":"80"}"}';
// This is the original string
let pass = '{"attribute_as":"plan_id","operator":"fromTo","values":{"from":70,"to":80}}';
// Corrected string

let desiredObj = {
    attribute_as: 'plan_id',
    operator: 'fromTo',
    values: {
        from: 70,
        to: 80
    }
};

console.log(JSON.stringify(desiredObj) == err);
console.log(JSON.stringify(desiredObj) == pass);

【讨论】:

    【解决方案2】:

    这应该可以解决问题。记录时都正确评估。

    let
        test = '{"attribute_as": "plan_id","operator": "fromTo","values": {"from": 70,"to": 80}}',
        test2 = {
            attribute_as: 'plan_id',
            operator: 'fromTo',
            values: {
                from: 70,
                to: 80
            }
        }
    
    console.log(JSON.parse(test));
    console.log(JSON.stringify(test2));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多