gpt4 book ai didi

javascript - Node.js 解析在接收 JSON 时返回未定义

转载 作者:行者123 更新时间:2023-12-03 05:28:17 25 4
gpt4 key购买 nike

我正在尝试解析 Node.js 服务器上传入的 JSON 对象,但它一直显示未定义?这是我的代码:

app.get("/adddates", function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log("does this get called?"); //Response 1 here is correct
console.log(query); //Response here 2*
console.log(query['name']); // Response 3 here is undefined?
if(query["Name"]!==undefined) {
var tx = { Name : query["Name"],
Description: query["Description"],
Date: query["Date"],
People: query["people"],
Tag: query["Tag"]

};
console.log(tx);
todos.push(tx);
console.log("Added " + tx.message);
res.end("Todo added successfully");
}
else {
res.end("Error: missing message parameter");
}
});

2* = { '[{"Name":"testetst","Description":"Blasts","Date":"2016-12-08","People":["Sjaak"],"Tag":"': '' }

所以我的问题是,为什么响应 3 未定义以及如何修复它?

另外为什么标签值是空的?输入的是十六进制颜色?这只是我做错的 JSON 解析吗?

提前非常感谢

最佳答案

如果你看url.parse文档你会看到这个:

┌─────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤
│ protocol ││ auth │ host │ path │ hash │
│ ││ ├──────────┬──────┼──────────┬────────────────┤ │
│ ││ │ hostname │ port │ pathname │ search │ │
│ ││ │ │ │ ├─┬──────────────┤ │
│ ││ │ │ │ │ │ query │ │
" http: // user:pass @ host.com : 8080 /p/a/t/h ? query=string #hash "
│ ││ │ │ │ │ │ │ │
└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)

所以json中的tag发送后会变成hash。要解决此问题,您发送的数据应该进行 url 编码。这可以通过 encodeURIComponent(URI) 来完成.

$.get( "localhost:3000/adddates", encodeURIComponent(dateobj) );

编辑如果你看query您会看到它像 query=string 一样解析数据。因此将查询部分添加到 url 字符串中:

$.get( "localhost:3000/adddates", "data=" + encodeURIComponent(dateobj) );

然后您应该能够检索数据,例如

var json = query["data"];
var data = JSON.parse(json);
var name = data[0]["Name"]

原始答案

假设 json 是

[{"Name":"testetst","Description":"Blasts","Date":"2016-12-‌​08","People":["Sjaak‌​"],"Tag":""}]

有不同的sites您可以在其中验证您的 json 是否正确。

那么查询是由[]指示的对象数组。要访问对象本身,您首先需要从数组中获取它们,然后才能访问属性。

query[0]["Name"]

关于javascript - Node.js 解析在接收 JSON 时返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com