JSON Parsing in Javascript & node - javascript

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..

Related

Covert stringified object of array to object in Expressjs

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))

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);

Html in json - how to make it valid (with javascript)?

I'm using json.net to automatically deserialize my json objects into .net objects. As long as the json is valid, it works a treat.
But I'm having trouble with html in the json...the special characters and quotes are making the json invalid.
How do I encode or escape the html reliably so it's valid json? I need a way to do it with just javascript because it's the client side sending to the server side.
Edit
Just to give an example of my use case, I have a WYSIWYG in my app and I need the input from that included as part of a json object to be posted to my server.
Just to give an example of my use case, I have a WYSIWYG in my app
and I need the input from that included as part of a json object to be
posted to my server.
Assuming you have the user input in a string variable:
var userInput = 'Any crap with HTML you can imagine';
You can simply JSON encode this in order to transport it as a valid JSON string:
var json = JSON.stringify({ value = userInput });
Now the resulting object will look like this:
{
"value": "Any crap with HTML you can imagine"
}
and on your server simply map this to a POCO with a plain Value string property. The JSON.stringify method will ensure to properly serialize any input to a valid JSON string.
This being said, I don't quite understand your need of wrapping the user input in a JSOn string and then deserializing it back on the server with JSON.NET. I would rather send the raw input as-is. This way you would get exactly the same value on the server without the overhead of JSON serialization.

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.

parse json object from server side

IN my web service,I return one json object in the method:
{name:'xx'}
I use the ajax to send the request,then parse them using the 'eval'
onComplete:function(req){
var data=eval(req.responseText);
//do something according data
}
However,I can not get the 'data'.
When I retrun the following string:
[{name:'xx'}]
It worked,and I get the 'data' as an array.
Through google,I know that it is caused by the '{' in the return string.
So I wonder if there is no way to retrun a json object ?
Use JSON.parse or jquery's $.parseJSON - if you use jquery - instead of eval.
Also, if you do use jquery, you can take advantage of the built-in ajax method that automaticly retrieves and parses the response as a json object : $.getJson.
If you still don't want to modify your "logic", you can try to eval your response with added brackets : var data = eval('(' + req.responseText + ')');
Have a read of this blog post on JSON hijacking. The author explains the issue your running into
You might have seen code like the following when related to JSON:
eval('('+JSON_DATA+')');
Notice the beginning and ending parenthesis, this is to force
JavaScript to execute the data as an object not a block statement
mentioned above. If JavaScript did attempt to execute JSON data
without the parenthesis and the JSON data did in fact begin with “{”
then a syntax error would occur because the block statement would be
invalid.
...more info on why...
Rather than adding () around your JSON response, you should be using JSON.parse or $.parseJSON like gion_13 has said. Eval isn't the way to go.
Also, like quentin said in the comments, you need to change the JSON you're returning as it's invalid. You need to quote your key as well as your value.
It worked,and I get the 'data' as an array.
That's what it's supposed to do. [] is the syntax for declaring an array. If you want the inner object, then just return {name: 'XX'}.

Categories

Resources