Reputation: 13
I'm trying to parse an incoming JSON object on my node.js server, yet it keeps saying it's undefined? Here is my code:
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":"': '' }
So my question is, why is response 3 undefined and how to fix it otherwise?
Also why is the Tag value empty? The input is a hexcode color? Is it just a JSON parse i'm doing wrong?
Many thanks in advance
Upvotes: 0
Views: 2024
Reputation: 456
If you look at the url.parse
documentation you'll see this:
┌─────────────────────────────────────────────────────────────────────────────┐
│ 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)
so the tag
in the json will become the hash after being send. To fix this the data you send should be url encoded. This can be done by encodeURIComponent(URI)
.
$.get( "localhost:3000/adddates", encodeURIComponent(dateobj) );
edit
If you look at the query
part you'll see it parses the data like query=string
. So adding the query part to the url string:
$.get( "localhost:3000/adddates", "data=" + encodeURIComponent(dateobj) );
Then you should be able to retrieve the data like
var json = query["data"];
var data = JSON.parse(json);
var name = data[0]["Name"]
original answer
assuming the json is
[{"Name":"testetst","Description":"Blasts","Date":"2016-12-08","People":["Sjaak"],"Tag":""}]
There are different sites where you can validate if your json is correct.
then the query is an array of objects indicated by the [
and ]
. To access the object itself you'll first need to get them from the array and then you'll be able to access the properties.
query[0]["Name"]
Upvotes: 1