javascript - 为什么 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/
解决方案
这是 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
}
推荐阅读
- objective-c - 在后台线程中完成方法后重新加载 UITableView
- c++ - 将 VS 2017 项目迁移到 Embarcadero
- c# - 如何在 UNC 文件夹中调用 BAT 脚本并避免 Win32Exception (0x80004005):操作已被用户取消
- android - 我应该将改造 API 响应存储在数据库中吗?
- php - mssql 和左连接重复记录
- python - 带有一行数据的 Pandas read_csv() 返回空数据框
- amazon-web-services - 为什么要为 RDS 使用 t2-medium 类型实例而不是 t2-micro?
- javascript - 使用 Firebase 身份验证和角度路由器进行路由
- odoo - 如何在 Odoo 中将 JS 添加到 Head 标签
- html - CSS:是否可以在保持布局的同时打破容器