I'm trying to replace the angularjs POST query with standalone JSON response string.
When angular GET / POST queries returns a response automatically converted to JSON and the code was working like charm.
Now, I'm trying to have the json response stored as a javascript string variable in the controller and then trying to parse it using JSON.stringify() and subsequently using JSON.parse().
There is no error but the resulting json object's member variables can't be accessed using the . operator
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
var resultString = JSON.stringify(staticData);
$scope.staticTestData = JSON.parse(resultString);
console.log($scope.staticTestData.masterJobs); // this displays 'undefined'
Controller function with the large JSON is available here.
You already have a string, so there is no need to use JSON.stringify.
Just use the following code:
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
$scope.staticTestData = JSON.parse(staticData);
console.log($scope.staticTestData.masterJobs);
Related
In the views.py:
data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder).
I pass data as context to the html file.
In the HTML file, Using JS I access the JSON object with this code:
{{ data|json_script:"hello-data" }}
<script type="text/javascript">
var data = JSON.parse(document.getElementById('hello-data').textContent);
document.getElementById('id_line_one').onchange = function(event){
console.log(typeof data)
alert(data);
document.getElementById('id_line_one_unit_price').value = data[this.value];
};
</script>
I expect the var data to be a dictionary but it seems to be a String. Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>).
JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. How can I convert it into a dictionary? Thanks
The problem is that you are obtaining a list from the following line:
data1 = list(Inventory.objects.values_list('product_number','amount'))
Hence, you are just converting a list to JSON and, then, parsing this JSON, which yields a list.
Try to use the following instead:
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
data_obj_model = Inventory.objects.all()
data1=serializers.serialize('json', data_obj_model, cls=DjangoJSONEncoder)
Then, you can access, in your JavaScript code, all the fields of the model using data["fields"].field_of_interest.
Or you can also create a custom dictionary with the two fields you were interested in as follows:
data1 = dict(Inventory.objects.values_list('product_number','amount'))
This could be used as a dictionary in the JavaScript after parsing it.
I am trying to figure out how to take an array of arrays and convert it to a json string to return via a REST api.
My server gets records from a database. Each record is in the form:
{"user":"some name","age":number}
I need to return the data in json format so that the REST specification is valid.
Sometimes I get a single record to return other times I get multiple records.
Below is a sample script I am using to test the syntax for converting into json format.
var resultSet = [];
resultSet.push({"user":"John Doe","age":43});
resultSet.push({"user":"Jane doe","age":29});
var myJson = JSON.parse(resultSet);
When I run this code using nodejs I get the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Any suggestions would be very appreciated.
JSON.parse expects a string. You are passing an Array.
This works because the input is a string:
JSON.parse('[{"foo": "bar"}]')
This doesn't work because the input is an Array:
JSON.parse([{"foo": "bar"}])
Are you trying to return an Array or a string? If you are trying to return a string, then you should use JSON.stringify like this:
JSON.stringify([{"foo": "bar"}])
I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.
I am trying to use codebird to get some data from twitter. I have a script in JavaScript.
My problem is that codebird's reply is an object and not a JSON. So I can't use eval() to get parse the json text in an array.
I just need to acces the json data.
Thank you in advance
var cb = new Codebird();
cb.setConsumerKey("", "");
cb.setToken('','');
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
data = eval(reply) //parse the returned JSON to array
}
}
);
If you need to convert a JavaScript object into a JSON string you can use
data = JSON.stringify(reply)
But usually it's better to deal with object itself - e.g. you can iterate thru it's properties (creating your own array if needed)
I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.