解析 JSON 字符串中的嵌套对象

Parse nested object in JSON string

我有这个代码:

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
    }
}

字符串不正确:

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);

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

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));