Covert stringified object of array to object in Expressjs - javascript

I'm sending stringified data from Angular using FormData like:
this.formData.append('data', JSON.stringify(this.collections))
How can I convert it back to object in my backend (Express)?
I'm getting data in req.body .
This is what I'm receiving in req.body.data:
[{"uid":"","description":"store","price":"777"},{"uid":"dd5adebf-06c6-4d6c-b005-2fcb0a2ca161","description":"blanketssdf","price":""}]
I cannot use application/json header since I'm using mutipart/form-data to send images.
I'm stuck at this since long. I've tried JSON.parse(), Object.assign() but nothing works.
console.dir() gives me the desired result but I want this result to be stored so that I can perform stuff on this.
Thanks in advance

I had it done using JSON.parse(new Object(req.body.data))

Related

Simple JSON stays undefined

I have an AJAX call that get's a simple JSON back on success, writing the returned JSON into the variable named data.
The returned JSON has been generated within PHP through:
echo json_encode(array('message'=>0);.
Back in my javascript console I'm logging the output of data with console.log(data);. The output is {"message":0}, which seems correct.
However, if I try to log console.log(data.message); I am getting message: undefined.
What am I doing wrong in accessing this pretty basic JSON object?
I've been reading some articles about how to move through JSON object, e.g. https://www.tutorialspoint.com/json/json_overview.htm but I can't find my mistake.
Hopefully you can point me into the right direction :)
Thank you :)
You have to do JSON.parse(result) first to make it an object, because at the moment you're trying to access message property of a string.
You know there are 2 JSON functions in javascript, right...?
// returns string representation of the object
JSON.stringify(object);
// returns a new object built from the string
JSON.parse(object_stringified);

Node.js can't get JSON Object property

I'm using Node v6.5.0. I have a JSON Object as the response of HTTP request and I need to get the body property. However if I try to get the body using res.body, I will get completely messed up result.
Because the JSON Object is too long, I can't post it here. Follows is the link of coderpad containing the JSON Object and the result when I access the body property
https://coderpad.io/6RNEMTJ3
The only body I can see in your coderpad link seems to be a string containing HTML. Which can't be parsed as JSON.

Receiving php data via ajax as an array instead of responseText in my javascript

Currently I have an ajax setup where my page with javascript calls a php file which then returns data via xhttp.responseText. This works great for strings but when I pass it a json encoded array, it still views that results as text. I get a string formatted version of my array that looks like this [1,2,3,4,5,6,7]
Which sort of works, but it's inconvenient because it's text representing an array and not an actual array.
How can I receive the data as an array instead of an array in text format? Currently I can still get the data using split(), but that seems sloppy. Is there an alternative to xhttp.responseText that would work better?
You can try sending your data as a JSON, which will give you all the flexibility in the kind of structure you want the data to have. PHP has the function json_encode which will convert your PHP variable into a JSON and you can receive this on the client side.
First, make sure your PHP encodes the JSON as I said and that you have the proper header set too, i.e.
header('Content-Type: application/json');
Next, in your AJAX code, do JSON.parse(xhttp.responseText) to retrieve the JSON data as JavaScript object.
Then you can do whatever you want with this object. Also, you can check your PHP is sending a JSON via xhttp.getResponseHeader("Content-type") which should return "application/json" if you are sending a JSON object.
You need to set header, smth like following
$data = array('1', '2', '3');
header('Content-Type: application/json');
echo json_encode($data);

JSON Parsing in Javascript & node

I am trying to parse a JSON Array that I posted from the client side to a node based server.
the json object holding the array looks like this
customData : {
"playlist": [
"//www.youtube.com/embed/bxq6SofU_38?rel=0",
"//www.youtube.com/embed/Qyqchamz4EM?rel=0"
]
}
However when I try to access the data using customData.playlist[0], it returns that it cannot parse 'playlist' the console reports that it is undefined.
I checked my JSON using the JSONLint validator and it said that me JSON was valid. I must be missing something pretty simple any thoughts?
if you get data from client side you should parse that like this:
var parsed = JSON.parse(recievedData);
and then you have access them.
Whenever response comes from a server or client ,the result will be in string.. Coz you know strings are easier to transfer within networks... Try to use JSON.parse. console the typeof of customData .. It must be object.. Then only you can.. Get values..

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

Categories

Resources