I'm sending a json object through ajax to a java servlet.
The json object is key-value type with three keys that point to arrays and a key that points to a single string. I build it in javascript like this:
var jsonObject = {"arrayOne": arrayOne, "arrayTwo": arrayTwo, "arrayThree": arrThree, "string": stringVar};
I then send it to a java servlet using ajax as follows:
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("Connection", "close");
var jsonString = jsonObject.toJSONString();
httpRequest.send(jsonString);
This will send the string to my servlet, but It isn't showing as I expect it to. The whole json string gets set to the name of one of my request's parameters. So in my servlet if I do request.getParameterNames(); It will return an enumeration with one of the table entries' key's to be the entire object contents. I may be mistaken, but my thought was that it should set each key to a different parameter name. So I should have 4 parameters, arrayOne, arrayTwo, arrayThree, and string. Am I doing something wrong or is my thinking off here? Any help is appreciated.
Thanks
When you set the content-type to application/x-www-form-urlencoded, you're telling the server that the request content is going to be a string of the form "param1=value1¶m2=value2...". But your actual content is just a single value; the x-www-form-urlencoded content type has nothing to do with JSON. If you want to pass the request as JSON, you'll need to set the content-type to application/json and then have a JSON parser on the server side to parse it and extract the key/value pairs.
Alternatively, you could keep the x-www-form-urlencoded type, loop through your JSON object and, for every key/value pair, serialize the value as a JSON string and URL-encode, and use that to build up a request string that looks like:
arrayOne=<arrayOne JSON string>&arrayTwo=<arrayTwo JSON String>&...
It is the expected behavior, you're converting your object to string (using toJSONString) and its is being send as a request parameter. You may want to parse the JSON value on the serverside using libraries such as Jackson, Jettison or XStream see http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Related
I've problem with serializing object using JSONRenderer.
I'm using django-rest-framework and I've serialized object:
pk = kwargs['pk']
tube = Tube.objects.get(id=pk)
serialized_tube = TubeSerializer(tube)
serialized_tube.data looks like this:
{'id': '11122211133311'}
Unfortunately I can't serialize this using JSONRenderer, because the code
tube_json = JSONRenderer().render(serialized_tube.data)
return Response(tube_json)
gives following error
b'{"id":"11122211133311"}' is not JSON serializable
whereas
tube_json = json.dumps(serialized_tube.data)
return Response(tube_json)
works well...
I'm using Python3.4.3
The issue is not in your JSONRenderer() line, but in the line below it where you return it as a Response.
Django REST framework provides a custom Response object that will automatically be rendered as whatever the accepted renderer was, converting native Python structures into a rendered version (in this case, JSON structures). So a Python dictionary will be converted to a JSON object, and a Python list will be converted to a JSON array, etc.
Right now you are serializing your data to a JSON string then passing it to Response, where you are expecting it to be re-serialized into JSON. You can't serialize a string into JSON (you need an object or array wrapping it), which is why you are seeing the error.
The solution is to not call JSONRenderer ahead of time, and just pass the serializer data to Response.
#SOLVED
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
I got a question
I`m building a function that receive parameters to write a list of parameters and send it by POST
The problem is that we can't send special characters, such is +
So I tried to use the function encodeURIComponent to encode them to a URI friendly string.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.
on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))
I have a javascript function that calls an external program and I need to put the result into an object, which will contain multiple rows with multiple values for each, example below:
$.get(programcall , function(data) {
var dealers = {};
data = {0:{'name':'name1','address':'address1','phone':'phone1','miles':1.2},1:{'name':'name2','address':'address2','phone':'phone2','miles':2.2}};
dealers = data;
});
This test works because "data" is not enclosed in quotes, however when the content of "data" is returned from the called program, it just becomes text content in "dealers".
How can I get the value stored as an object?
The called program is MINE, so I can change the format if necessary to make it work.
The data will be a list of customers with name, address etc, which I want to process using javascript and to populate a DIV.
If the string is valid JSON, use the native JSON.parse function to turn it into an object.
For example:
data = JSON.parse('{"mything": 3}')
One thing to look out for: JSON needs double quotes around key names, so {"mything": 3} works but {'mything': 3} will not validate.
Your external server call is returning string content as the data object. This is, hopefully, a valid JSON format but it is still just a string.
What you probably want to do is use jQuery's getJSON function instead of a simple $.get, since it will take care of converting the response to a JSON object similar to your example.
$.getJSON(programcall, function(data) {
// data is now a JSON object not a string, if it's valid json from your server response
I have a javascript object which I want to pass to a PHP file while using jQuery's ajax-implementation.
I've tried to directly pass it to it but this doesn't work, because it isn't escaped or anything. I've tried to use JSON.stringify but this isn't working for me either.
Is there a way to 'serialize' a javascript object to a POST-string?
Update, I'm using JSON.stringify() again. The result is:
The result of JSON.stringify() is:
{\"label\":\"Borne, Overijssel, Nederland\",\"value\":\"Borne, Overijssel, Nederland\",\"geocode\":{\"address_components\":[{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"Overijssel\",\"short_name\":\"OV\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"Nederland\",\"short_name\":\"NL\",\"types\":[\"country\",\"political\"]}],\"formatted_address\":\"Borne, Nederland\",\"geometry\":{\"bounds\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}},\"location\":{\"Ya\":52.3002366,\"Za\":6.753725799999984},\"location_type\":\"APPROXIMATE\",\"viewport\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}}},\"types\":[\"locality\",\"political\"]}}
When I do a json_decode it results to NULL. Any suggestions?
If your passing an object as a string thats in legitmate JSON format, to PHP try using
json_decode() on the php side of things. Example
<?php
$ojb = json_decode($_POST['my_json_string']);
?>
What this will do is turn your object into an array or object depending on which version of PHP you are using, and in some cases the object will turn into an array with multiple objects in it.. example:
Array(
[0] stdClass (
'key1'=>'val1'
'key2'=>'val2'
'key3'=>'val3'
)
)
which I know the above isnt a good representation, but its a representation in the lines there of.
After that PHP side you can work with the variable $ojb like any other array/object.
$something = $ojb[0]->key1;
EDIT
I notice your string now. The fact that the quotes are escaped in the string, breaks the fact that its a JSON object, with that you can do one of two things.. Either just pass the object to PHP through your post/get as is, without running it through strigify or.. you could try on the PHP side, if there is a need to strigfy it..
$ojb = stripslashes($_POST['my_json_string']); $ojb = json_decode($ojb);
which will attempt to remove the slashes from the quotes, before putting it through the decode process.
http://php.net/manual/en/function.json-decode.php
You can specify a raw body of the POST request. The raw data would be the result of a JSON.stringify call which would mean that you should specify an appropriate Content-Type header.
$.ajax(url, {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
processData: false // prevent escaping and other processing
});
You can then deserialize the object in PHP like this:
$json = file_get_contents('php://input');
$data = json_decode($json);
The raw request body is mapped onto the special path php://input
I have
var pageData = {
query: null,
pageNumber: 0,
pageSize: 30};
When I make an ajax get:
$.ajax({
type: 'GET',
url: '/Ajax/GetSuggestions',
data: pageData,
success: function (response) {}
The request show in firebug: http://localhost:31198/Ajax/GetSuggestions?query=null&pageNumber=1&pageSize=30
At server side (ASP .NET MVC3), I received query = null in string, not null data(what I need).
How can I fix it without using delete method of javascript to remove null value?
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?query=&pageNumber=1&pageSize=30
Then, you have to set query property to "" (an empty string).
If you want your URL to look like this:
http://localhost:31198/Ajax/GetSuggestions?&pageNumber=1&pageSize=30
Then, you have to remove to remove the query property from the pageData object by either not putting it there in the first place or by using delete pageData.query to remove it.
There are multiple ways to send data "over the wire". The standard one for sending form data to the server is url encoding. A second way is to send a JSON object. (A transmission detail is that the JSON would be url-encoded. But that's only a transmission detail.) A third way is to use XML.
As #jfriend00 shows in his answer, there are multiple, hacky ways to send a "null" value via url encoding. You should use the one which your server side stack best supports.
Re: why the string "null" What's happening is that the Javascript value null needs to be converted to a value that can be sent via HTTP ("over the wire"). The default way to do that is to use the string null. The problem is that the url encoding scheme only sends things as strings. So it doesn't have an automatic way to send the value null vs teh string null. The usual work around is an empty string, "".
But this can also raise an issue on your server-side since the string "" is not equal to the value null in most computer languages. So you will need to make appropriate comparisons or conversions. Eg does "" == false in your server software?
Using JSON for the data encoding is the other technique.
JSON directly supports a null value. It is is supposed to transmit it as null. See JSON spec (not so obvious, search the page for null) and IBM docs
The way you receive null data in JSON is the bareword null. If you're using JSON, note that you do not receive the string null, you receive the JSON keyword null. Your JSON receiver/decoder should know the difference. If it doesn't, then it is faulty.
When the request string is being built in jQuery, it's using every property on the data object it can find.
All you need to do to remove a property is delete the property:
delete pageData.query;