首页 > 解决方案 > 为什么 JSON.parse(str) 变成 String?

问题描述

我尝试使用JSON.parse();将字符串解析为 JavaScript 对象,但是当我调用console.log(object.constructor.name);之后,它给了我“字符串”。

我尝试使用parse两次而不是一次,但后来它给了我一个错误。

var userInput = document.getElementById("userInput");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
var dataString = "";
const endpoint = 'https://www.jsonstore.io/4037b406bb44de85c5dd50eb1a6472bedb79f447e747412695637c2784cbe43f';

function writeToDatabase(arr) {
    alert(arr);
    (async function() {
            // Send a post request, saving some data
            post_response = await fetch(endpoint, {
                    method: 'POST',
                    headers: {
                            'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(arr)
            });
            /*
            // console.log the result
            console.log(`POST response:`, await post_response.json())
            */
    })();
}
function readFromDatabase() {
    fetch(endpoint)
    .then(response => response.json())
    .then(data => {

    console.log(data);
        dataArr = data;
        console.log(dataArr);
  });
}

yes.onclick = function() {
    fetch(endpoint)
    .then(response => response.json())
    .then(data => {

        data = JSON.stringify(data);
        console.log("full data: " + data);

        data = JSON.parse(data);
        data = data['result'];

        data = JSON.stringify(data);
        console.log("result array only: " + data);

        data = JSON.parse(data);// object.contructor.name
        console.log("after parse: " + data);
        console.log("data type is: " + data.constructor.name);

        data[userInput.value] = "YES";
        console.log("final string to write to database: " + data);
        writeToDatabase(data);
    });
}



no.onclick = function() {
    dataString = "{"+userInput.value+": "+"NO"+"}"
    writeToDatabase(dataString);
}

我希望它能够转换为 Javascript 对象,这样我就可以添加一个项目,但相反,它仍然是一个字符串,所以我不能添加一个项目。

代码:https ://repl.it/@ErichBuelow/JsonStore-using-JS 查看:https ://jsonstore-using-js--erichbuelow.repl.co/

标签: javascriptjavascript-objectsjsonstore

解决方案


这是 URL 上的数据:

{"result":"{test: NO}","ok":true}

response.json()然后将其转换为具有两个属性(result(字符串)和ok(布尔值)的 JavaScript 对象。

data = JSON.stringify(data)将其转换回 JSON,反转response.json().

data = JSON.parse(data);再次反转它,为您提供上述对象更多。

data = data['result'];提取result属性,给你字符串"{test: NO}"

data = JSON.stringify(data);为您提供该字符串的 JSON 表示。

data = JSON.parse(data);反过来又给你字符串。

我尝试使用 parse 两次而不是一次,但是它给了我一个错误。

目前尚不清楚您在哪里尝试过此操作,但如果您尝试解析{test: NO},则会出错,因为该字符串不是有效的 JSON。{ "test": "NO" }将是有效的 JSON,但缺少引号。

将 JSON 字符串嵌入 JSON 中只是愚蠢的。最好将原始 JSON 表示为:

{
    "result": {
        "test": "NO"
    },
    "ok": true
}

推荐阅读