【问题标题】:Why does JSON.parse(str) into String? [closed]为什么 JSON.parse(str) 变成 String? [关闭]
【发布时间】:2019-12-23 17:39:49
【问题描述】:

我尝试使用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/

【问题讨论】:

  • 您能否尝试创建一个您正在处理的工作示例,并至少分享一个响应示例 -> JSON 您正在使用。谢谢。
  • 我以为它会给我对象?
  • 在哪里?更具体。整个问题太模糊了
  • 不确定,但我认为你不需要解析任何东西,你已经有了一个 Body.json as response... 所以你可以直接用 JS 对 data Object 进行操作!
  • 所以最终目标是更新数据库上的对象,所以我试图读取旧数据,将其解析为对象,添加到对象,然后解析为字符串并覆盖数据库中的旧的

标签: javascript javascript-objects jsonstore


【解决方案1】:

这是网址上的数据:

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

【讨论】:

  • 我根据你的回答修改了一些代码,效果好多了,谢谢。
  • 我遇到了一些麻烦,因为在出​​现以下错误之前我最多只能添加 2 条数据: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ()
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 2023-03-10
  • 2013-01-28
  • 1970-01-01
  • 2013-03-08
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多