【问题标题】:JSON object parse issue on react反应中的JSON对象解析问题
【发布时间】:2017-12-10 20:37:28
【问题描述】:
json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";  
   json = JSON.stringify(json);
   model = new Model(json);

当它有引号时它不会识别 json 对象

 var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";

删除引号时有效

   json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}; 

我试过 JSON.parse(json);没用,请问有大神推荐解决方法吗?

【问题讨论】:

    标签: javascript jquery json string reactjs


    【解决方案1】:

    如果字符串中有 JSON,则应该使用 JSON.parse,而不是 JSON.stringify

    此外,单引号在 JSON 中无效,因此请始终使用双引号。

    // I fixed the JSON
    var json = '{ elements: [ {type: "radiogroup", choices: ["Yes","No","Maybe","Never"], isRequired: true, name: "Test_01", title: "Do you like ice cream?" }],showQuestionNumbers: "off"}';
    // The thing you would expect
    var obj = JSON.parse(json);
    

    【讨论】:

      【解决方案2】:

      因为您正在尝试对字符串进行字符串化,所以对象删除“”并且它将成为对象,然后尝试 JSON.stringify 和 JSON.parse 不起作用,因为数据不是正确的 JSON 字符串格式。例如:

      var object = '{"e":"a"}'; 然后使用 JSON.parse(object); 这会将您的字符串转换为对象。

      【讨论】:

        猜你喜欢
        • 2014-08-23
        • 2013-02-16
        • 2018-07-18
        • 2020-12-08
        • 2015-09-04
        • 1970-01-01
        • 2023-03-23
        • 2014-01-21
        • 2019-08-26
        相关资源
        最近更新 更多