Should backbone receive escaped JSON? [duplicate] - javascript

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.

Related

Serializing a model as Json in Django and parse it with JavaScripts JSON.parse

I am afraid I don’t understand what "serializing" means. If someone can explain I’d be grateful. I am serializing a Django model in Json as explained in the Django Docs:
data = serializers.serialize("json", MyModel.objects.all())
In my HTML/JS I access the data as recommended:
{{ data|json_script:"data" }}
var myData = JSON.parse([document.getElementById('data').textContent]);
But instead of being an Object myData is a string. So I guess somehow I serialize twice or something.
I found a solution, JSON.parse works as expected on my data now:
data = json.loads(serializers.serialize("json", CoursePage.objects.child_of(self).live().public()))
But I guess I still don’t understand the meaning of "serializing" properly. The Python docs say about json.loads(s): "Deserialize s (a str instance containing a JSON document). Why do I have to deserialize before JSON.parse works? The description for JSON.parse states: "The JSON.parse() method parses a JSON string"? Which I thought Djangos serializer would gave me in the first place. I am confused.
The json_script filter is for Python objects. But serialization is already the conversion of Python objects into JSON. So effectively you're converting it twice.
In your case I wouldn't bother with that filter. Just remove the json.loads and output the data directly where you need it:
var myData = JSON.parse("{{ data|safe }}");

Suitescript, nlapiRequestURL, can't turn a JSON from a URL into an object/array

In netsuite i'm using the nlapiRequestURL to retrieve a JSON data from flexport, an overseas shipping company. I have have the data as a string(to my knowledge retrieving json data makes it a string) and want to turn it into an array of objects, but everything I have tried has resulted in various errors.
trying...
`var output = nlapiRequestURL(url,null,headers,"GET");
var split = JSON.parse(output.getBody());
response.write(split);`
gave me
{records=[Ljava.lang.Object;#7220fad}
and trying to show any element of split gave me undefined or that it cant read element from index.
I've ran the string through a JSON checker and it said it was a valid JSON file. I've done various variations of JSON.parse and looked tried Tostring. I've been working on this for a while and have no idea why I can't parse this information properly. Any help is appreciated.
You have parsed the result but then you are writing the parsed object which just gets you the object’s implementation dependent toString() output.
If you are just trying to echo the response re-stringify the parsed payload.

JSON Array from String

I have an array of JSON plots which I store in MySQL. When I retrieve this information from MySQL it is given as one long string. How can I restore this back into an array of JSON objects using Javascript? I'm running this using NodeJS and MySQL package.
My data is returned like the following:
'[{"x":0,"y":0},{"x":1,y:1},{"x":2,"y":2}]'
What I would like to be able to do is use the data like:
var data = [{"x":0,"y":0},{"x":1,"y":1},{"x":2,"y":2}];
console.log(data[0].x);
I've had a try using JSON.parse and originally stored the data using JSON.stringify on the array, but it is not behaving as I would expect.
Are there any methods or packages available to handle this?
Edit: I realize now that this is not JSON but rather objects. Apologies for the wrong terminology here, but my problem still remains.
var data = new Function ('return ' + dataString)();

Populate Javascript Object With Data Returned From Program Call

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

Dictionary Object confusion from jQuery to Django!

I'm attempting to send a dictionary from jQuery to Django using a getJSON call:
jQuery.getJSON(URL,JSONData,function(returnData){});
The JSONData object is formatted as follows:
JSONData = {
year:2010101,
name:"bob",
data:{
search:[jim,gordon],
register:[jim],
research:[dave],
}
}
This is put together programmatically but looks fine.
Once passed to Django the "year" and "name" objects are as expected. The data object however contains the following keys/values - "search[0]":"jim", "search[1]":"gordon","register[0]":"jim","research[0]":"dave", rather than the expected "search":(array of data), "register":(array of data), "research":(array of data).
Similar things happen if I use objects in place of the arrays.
Is this an issue with Django's interpretation of the object?
Any idea how I might correct this...cleanly?
EDIT:
I have now simplified the data to make testing easier:
JSONData = {
year:2010101,
name:"bob",
search:[jim,gordon],
register:[jim],
research:[dave],
}
request.GET is not an instance of a normal python dict, but of the django class QueryDict, that can deal with multiple values for one key. If you need multiple values for a key returned as a list you have to use getList!
EDIT: Also have a look at this jQuery parameter settings!

Categories