Parsing a django object in template with javascript - javascript

I am attempting to read a Django object in javascript. I have serialized the django model object like so:
recent_data = leafSamples.objects.filter(field_name=str(fields_distinct[0])).latest('id')
recent_data_json = serializers.serialize('json', [recent_data])
Next I have tried to parse the JSON data in javascript:
var recentData = {{recent_data_json |safe}};
parsedData = JSON.parse(recentData);
console.log(parsedData)
However, I keep receiving an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
When stringified, my data looks like this:
[
{
"fields": {
"copper": "21",
"guess": null,
"zinc": "32",
"chloride": "",
"potassium": "2.36",
"irrigation": null,
"manganese": "19",
"calcium": "1.81",
"iron": "66",
"magnesium": "0.37",
"nitrogen": "3.14",
"boron": "46",
"date": "2018-04-08",
"sulfur": "0.33",
"field_name": "104A",
"age": null,
"phosphorus": "0.40"
},
"model": "scoutapp.leafsamples",
"pk": 1126
}
]
How can I parse my data in the "fields" property? I would like to be able to have parsedData.copper return "21," or something to that effect. Thanks!

JSON.parse parses strings, but you are feeding it with a list. You may try adding single quotes and escapejs filter:
var recentData = '{{recent_data_json | safe | escapejs }}';

Related

How do i access my json array with key named "data" in javascript?

I have json response returned from a rest api as below
{
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
I use jsonparse to convert it into object in javascript as below
var obj = JSON.parse(e.data)
When i access obj.extra.message it prints "Hello".
But when i try to access obj.data[0] , i get [object][Object] ,
seems like its taking "data" as a keyword?
How can i overcome this?
Note that you have your object inside an array.
Javascript doesn't show the whole object; you must use object's keys to access its data.
Obj.data[0] is the whole object.
It seems that your response is already JSON. So don't parse it again:
const data = {
"data":[
{
"id":"86",
"name":"Hello",
"last_name":"world"
}
],
"extra":{
"message":"Hello",
"additionalmessage":"world"
}
}
console.log(data["data"][0].name);
The parsing is working just fine; it's just that when you output the first element, you're just outputting the object, not one of its properties. The default toString on an object outputs [object Object]
You can try this:
var user = obj['data'][0];
console.log(user.name);
console.log(user.last_name);
Or try
JSON.stingify(obj.data[0])
here's how you can do it:
var obj = {
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
console.log(obj["data"][0]["id"]);

JSON.parse(). Accessing data and using it to populate dom

JSON.parse Syntax: JSON.parse(text[, reviver]) Parameters: text-The string to parse as JSON. reviver- Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object corresponding to the given JSON text.
I really don't understand this. I have a JSON file that I need to use the data within to populate the DOM but I don't understand JSON.parse. When I tried to use this I used
var myData = JSON.parse({ "site": { "id": "example", "name": "example1" }...etc});
then tried to access it using dot notation.
console.log(myData.site.id);
I don't know what I'm doing, I've now figured out 200+ ways not to do it
JSON.parse expects a JSON string as its parameter, but you are passing javascript object literal, which is an object already and does not need parsing.
Depending on your use case you can either add quotes to make the parameter string:
var myData = JSON.parse('{ "site": { "id": "example", "name": "example1" }}');
Or don't use JSON.parse at all and you can work with your object directly.
var myData = { "site": { "id": "example", "name": "example1" }};
Pass JSON string to JSON.parse(yourJSONString) Then you can get values by call headers as follows.
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
Then
myRst.site.id
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
console.log(myRst.site.id)

How to Get key value from parseJson()

I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);

Unable to access js property

I've json in this format :
[
{
"_id": {
"$oid": "560c079e1691682b4ff327ad"
},
"year": "2015",
"month": "9",
"day": "30",
"time": "17:02:17",
"problemDesc": "test",
"resolution": "test",
"IM": "test"
}
]
I'm attempting to access the year using : console.log(json[0].year) but receiving undefined. How to access the year value from this json string ?
fiddle :
http://jsfiddle.net/b8dggkof/
In the JSFiddle the value inside json is a string and not a JavaScript Object, you have to parse the string before try to access the value:
var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');
console.log(json[''][0].year);
After you parsed the string, you need to access the object with key an empty string:
json['']
The value associated to this key is an array and you need the first element, so:
json[''][0]
Now you can get the year:
json[''][0].year
You need to put in a key for the JSON and then access by the key the inner Object, after you parse it since it is a string enclosed in quotes '
var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'
console.log(JSON.parse(json)['key'][0].year);
you need to parse you json string to json object by using JSON.parse then use key name in you case which is ''(empty string)
var jsonStr = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parseJson = JSON.parse(jsonStr);
alert(parseJson[''][0].year)

javascript retrieve value from json

How to get value from [object Object] in javaScript.
i have a json response from php which i pass in javascript .
i want GPSPoint_lat,GPSPoint_lon all value.
var jArray = ;
var obj = JSON.parse(jArray);
i got [object Object] how i retrive the all value from obj.
my json string is-
{
"Account": "dimts",
"Account_desc": "Adminstrator",
"TimeZone": "Asia/Calcutta",
"DeviceList": [
{
"Device": "dl1pb1831",
"Device_desc": "DL 1PB 1831",
"EventData": [
{
"Device": "dl1pb1831",
"Timestamp": 1387790572,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:52",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.52802,77.14041",
"GPSPoint_lat": 28.52802,
"GPSPoint_lon": 77.14041,
"Speed": 12.9,
"Speed_units": "km/h",
"Heading": 193.6,
"Heading_desc": "S",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
{
"Device": "dl1pb7520",
"Device_desc": "DL 1PB 7520",
"EventData": [
{
"Device": "dl1pb7520",
"Timestamp": 1387790574,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:54",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.56589,77.05268",
"GPSPoint_lat": 28.56589,
"GPSPoint_lon": 77.05268,
"Speed": 29.9,
"Speed_units": "km/h",
"Heading": 91.4,
"Heading_desc": "E",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
Look at javascript tutorial
obj['key_name']
JSON objects work as an array. You can access to an element with a key:
obj['Account'] // returns dimts
obj.Account // works also
You should read some tutorial about it, like JSON: What It Is, How It Works, & How to Use It
Please retrive the value as
var jArray = <?php echo json_encode($_SESSION['return'] ); ?>;
var obj = JSON.parse(jArray);
var value=obj.Result;
I have zero experience in php so I don't know what's the resulting object from your first line of code. But assuming jArray is a json object with the structure defined in your question...you access its values as shown below...
jArray.Account;
jArray.DeviceList[0].Device; //access the device property of the first object in the DeviceList array
jArray.DeciveList[0].EventData.StatusCode;

Categories

Resources