Confused with JSON data and normal data in Django ajax request - json

I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
From where the function is getting format variable
Does format is json mean that data given to function is json or data which will be recived is json
Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all())
How will I use that data when i get that response in jquery function
If i don't use JSON in above function then how will the input and response back will chnage
Thanks

From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept: header that requests can use to indicate the preferred Content-Type for the response. On the client, you might use xhr.setRequestHeader('accept', 'application/json') to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending on how complicated your request needs to be, you can use jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can use jQuery.parseJSON to process the json data, and that will return the same JavaScript objects.

From the urlconf, just like it says in the article right below it.
The query set will be serialized as JSON.
It will be the query set represented as either XML or JSON. python manage.py shell is your friend.
You will decode it, then iterate over it.
You'll need to find some other format to serialize it in instead.

Related

passing variable to json file while matching response in karate

I'm validating my response from a GET call through a .json file
match response == read('match_response.json')
Now I want to reuse this file for various other features as only one field in the .json varies. Let's say this param in the json file is "varyingField"
I'm trying to pass this field every time I am matching the response but not able to
def varyingField = 'VARIATION1'
match response == read('match_response.json') {'varyingField' : '#(varyingField)'}}
In the json file I have
"varyingField": "#(varyingField)"
You are trying to use an argument to read for a JSON file ? Sorry such a thing is not supported in Karate, please read the docs.
Use this pattern:
create a JSON file that has all your "happy path" values set
use the read() syntax to load the file (which means this is re-usable across multiple tests)
use the set keyword to update only the field for your scenario or negative test
For more details, refer this answer: https://stackoverflow.com/a/51896522/143475

Make a JSON object Without Quotes on the beginning and end of the string

I'm using React and fetch, and I'm trying to send a JSON string to a client's web service, they are expecting an object like this:
{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}
However, whenever I use JSON.stringify() to generate the JSON string, the result is something like this:
"{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}"
So when the request is sent, I get back an error stating that the object is not valid.
Is there a way to send the object like on the first example? I've tried manually building the object, but I can't get the key's names to stay in quotes.
EDIT: The code for the call is here:
addToCart(plan) { //Plan is the object with the previous example's structure
fetch("http:ClientWS", {
method: "POST",
body: JSON.stringify(plan) //Produces the "{}" issue
})
.then(response => response.json())
.then(json => {
//Read the response info, here it tells me that the value for 'id' is invalid
console.log(json.datos);
}).catch(function(ex) {
console.log(ex);
});
}
JSON.stringify() does not add extra quotes around the output. If you are seeing those extra quotes, I would say that it implies that the error is somewhere else.
That's because JSON.stringify takes your object and outputs a string variable by concatenating all the properties and values together and inserting some separators. And a string is displayed in quotes, again because it's a string. It's not an object any more. When you send it to the server, the server will see it as a single string value. The fact that the content of the string happens to look like JSON is not taken into consideration.
You do know that JSON and JavaScript objects are essentially the same thing? The stringified JSON that you can see is just a human-readable version of the object structure. It also turns out to be a convenient format in which to serialise objects (from all languages not just JS) for transmission in a HTTP request (or storage in a file or database, among other uses).
So actually when you send your object to the server, do just that - send the object. If you're doing it via ajax, the JS code you're using will generally serialise it for transmission on your behalf. You may have to set the correct content type header. That serialised object inside the HTTP request's body will end up looking a lot like the output of JSON.stringify (if you viewed it in your browser's network tab, for instance), except it won't actually be a string, and the server will interpret it correclty as an object containing multiple properties.

Accessing data from API json response. Arrays? Laravel

I am trying to access the steamid data in a json response returned by an API, specifically the Steam API.
The responses look like this:
I've made it return json but why do I see array all over the place?
How would I access the steamid data? I'm getting a bit confused as I thought this would be json.
I'm using guzzle to get the data and converting it to json using the guzzle json() method:
Any help would be appreciated.
Thanks!
The API is indeed using JSON to send/receive , however JSON is just a string, so in order to use that data PHP must parse it, which is automatically handled by guzzle, so as soon as you get the data back it has automatically decoded the data into a usable format for yourself.
It does this using the json_encode() and json_decode() functions.
You'd be able to access the steamid with the following.
// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);
foreach($players as $player)
{
$steamId = array_get($player, 'steamid', null);
}
Using the laravel helper array_get() function is a great way of ensuring you return a sane default if the data doesn't exist as well as eliminating the need to keep doing things like isset() to avoid errors about undefined indexes, etc. http://laravel.com/docs/5.1/helpers
Alternativly not using the laravel helpers you could use something similar to below, although I'd advise you add checks to avoid the aforementioned problems.
foreach($data['response']['players'] as $player)
{
$steamId = $player['steamid'];
}
If you didn't want guzzle to automatically decode the API's JSON I believe you should just be able to call the getBody() method to return the JSON string.
$json = $response->getBody();

ZF2: What's the easiest way to return a boolean json response?

In ZF1 it was pretty easy to send a json boolean response, for example, in the controller use:
return $this->_helper->json(true);
What's the easiest way to repeat this in ZF2?
I tried creating a new JsonModel with an array of variables. The only entry in the array was my boolean value (with a key of 0). This didn't work because the resolver was still off looking for a template.
I think I somehow need to return early?
EDIT:
I think this is a really important issue. For example, when the JQ Validation plugin uses a server-side validation method, it expects a JSON boolean response.
I managed to make my application JSON-ready by following 'alternate rendering and response strategies' section at the bottom of the Zend\View page, http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html. But this operates on the array that has been passed to the view, so the boolean true becomes json [true]
I tried the json view helper in various combinations, but couldn't get it to work.
Perhaps I need to create my own rendering and response strategies? That seems like overkill though...
Rob Allen has written an article about it:
Returning JSON from a ZF2 controller action
Also you can try this code to return every data without view rendering:
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;
The easiest way:
echo "true";
exit;
Though you may want to output some appropriate headers.
Arguably the correct way would be to add the JsonStrategy as viewstrategy and use a JsonModel, but I think it always returns an object (the json_encoded associative array of view variables passed to the JsonModel).

Wrapping JSON payload with key in EmberJS

Ok basically I am sending a POST request with some JSON payload in it to Codeigniter. I use RESTAdapater. JSON get sent there with no key, so I have no access to it.
Here is model:
App.Bookmark = DS.Model.extend({
title: DS.attr("string"),
url : DS.attr("string")
});
Here is controller:
App.BookmarksNewController = Ember.ObjectController.extend({
save: function(){
this.get("model.transaction").commit();
this.get("target").transitionTo("bookmarks");
}
});
In REST implementation in CI that I use standard way to access the post request is $this->input("key"). But when the above request is generated, only raw JSON data is sent. Therefore I don't seem to have a way to reference it in any way.
Take this example:
function post(){
$this->response(var_dump(file_get_contents("php://input")),200);
}
Gives me this output:
string(48) "{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
what I would like to see is:
string(48) payload="{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
Then is server I would be able to access this JSON with something like $this->post("payload").
So 1 of 2. Anyway to wrap the JSON payload with key? Or anyway to access raw JSON data in CI with no key available??
Ok figured it out myself (or rather read properly the examples).
When using Adam Whitney's fork of Phil Sturgeons REST controller for CodeIgniter the JSON payload will be available in $this->_post_args. And in the underlying implementation he uses my already mentioned file_get_contents("php://input").
EDIT: Same convention applies for other type of requests as well, for example DELETE request data will be available in $this->_delete_args. Or $this->_args is the "magic" place where all types of args can be found.