Retrieve nested javascript objects in Django view as a dict - javascript

I have a very simple view that receives an ajax request containing a javascript object. The jquery request looks like this:
$.get(URL, {'kwargs': {test: 1}}, function(data){//whatever})
The problem is, request.GET now contains a rather strange key and looks like this:
{'kwargs[test]': [1]}
How can I successfully decode this? As a side note, it is impossible to know the key (test) beforehand
The expected format obtained is a python dict that looks like the one in the request.
I've tried:
request.GET.get('kwargs', None)
And I'd expect this as a result:
{'test': 1}
However, I get None, as the real key is 'kwargs[test]'
EDIT
I know I could use some kind of regex to accomplish this, but it feels as 'reinventing the wheel', as this use case is not that rare

I would recommend using JSON when communicating back and forth between the server and client for this type of situation. JSON is meant to handle these types of nested structures in a uniform manner.
Take a look at using the jQuery $.getJSON functionality,
http://api.jquery.com/jquery.getjson/
The following is an example of how this structure would look...
Javscript
var request_data = {kwargs: {test: 1}};
$.getJSON(URL, {data: JSON.stringify(request_data)}, function(data){//whatever})
Django
import json
def your_view(request):
my_json = json.loads(request.GET['data'])
Doing this will allow you to parse the request which contains JSON data into a variable of your choice (my_json). Once you assign your variable with the results of json.loads(), you will now have a python object containing the parsed requested JSON data and you will be able to manipulate your object accordingly.
>>> my_json['kwargs']
{u'test': 1}

Related

Reading and Writing from Json File using Python and Javascript

I am supposed to read one Python data structure, a 2d list to be precise into a javascript function. I came to know that this could be done after converting the python data structure into a json object and then reading the json object back using Javascript function. I am rendering the html page using the Python script as you can see below.
import webbrowser, json
f = open('World.html', 'w')
arr = [[]]
arr[0].append('Hello')
arr[0].append('There')
arr.append([])
arr[1].append('Good')
arr[1].append('Morning')
arr[1].append('!')
message = '''<html><head><script type="text/javascript" src="outputjson.json"></script><script>function Hello(){alert(outputjson.arr);}</script></head><body><h1>This is not working and you know it</h1><input value="Click Bro" type="button" onclick="Hello();"></input></body></html>'''
f.write(message)
with open('outputjson.json', 'w') as f:
json.dump(arr, f)
f.close()
webbrowser.open_new_tab('World.html')
Outputjson.json look something like this:
[["Hello", "There"], ["Good", "Morning", "!"]]
The json object is successfully created but I am unable to read it back through my javascript function. Where am I going wrong ?
I have a constraint, I can't go for BeautifulSoup.
Thanks in advance.
You can't simple load json file into browser like that. One way is to make a XHR request to the json file and load it. The other way is to convert your json to jsonp structure.
jsonp_structure = "hello(" + json.dumps(arr) + ")"
f.write(jsonp_structure)
With the above change your hello javascript function will get called with the JSON. You can choose to store the JSON for further access/processing.

Read JSON String Shown In URL Using Javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

Issue with JSON.parse , don't know why is not parsing everything

I'm developing a web app with Node.js using Sails framework(based on Express) and i'm using a third party image solution called Transloadit (no need to know Transloadit).
Anyway, that's not the problem, i'm been able to implement the Transloadit form and receive the information from their API.
My problem is that, Transloadit gives me the response as a String, and I need to access the response objects, so i'm using var objRes = JSON.parse(req.body.transloadit); to parse it to an JSON object, and when I console.log(objRes); the object is not correctly parsed, i get this: (see all JSON here https://gist.github.com/kevinblanco/9631085 )
{
a bunch of fields here .....
last_seq: 2,
results: {
thumb: [
[
Object
]
]
}
}
And I need the data from the thumb array, my question is, Why is doing that when parsing ?
Here's the entire request req.body object: https://gist.github.com/kevinblanco/9628156 as you can see the transloadit field is a string, and I need the data from some of their fields.
Thanks in advance.
There is nothing wrong with the parsing of the JSON -- in fact there is no problem at all.
consol.log limits the depth of what it is printing which is why you are seeing [object] in the output.
If you want to see the full output in node.js then just use the inspect utility like this;
console.log(util.inspect( yourobject, {depth:null} ));
and that will print the entire content.
Note that this is just an artifact of console.log printing it.

Key and value reversed in JSON string sent to Django view via POST

This is my first attempt at ajax, and I've written a submit handler that parses a form and sends the data via POST to the server as a JSON string. Here is a simplified example of what my javascript looks like
formData = JSON.stringify({'testA':{'testa':'some data'},'testB':{'test2':'more data'}});
The JSON string looks like this
{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}
and I send it via post here
$.post("/some/form/page/",formData,updateForm,'json');
On the server side is where the problem rears its ugly head, this is what my query dictionary looks like when I print if from the Django view
<QueryDict: {u'{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}': [u'']}>
The JSON string is the key of the query dictionary. I am not very familiar with Javascript or JSON so don't be afraid of hurting my pride by pointing out an obvious newbie mistake, because I am and I know it. ;)
Thanks,
You're sending the string as a parameter to $.post. Instead of calling "JSON.stringify()" yourself, just pass in your raw JavaScript object as the second parameter to $.post().
$.post("/some/form/page/", {'testA':{'testa':'some data'},'testB':{'test2':'more data'}}, updateForm, 'json');

JQuery and JSON

Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.

Categories