Unable to access js property - javascript

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)

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"]);

Parsing a django object in template with 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 }}';

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 do i convert a JSON string to an array with objects with

I want to convert the following string to an array
[{id: "1", type: "railroadCrossingSign", latitude: "55.647432", longtitude: "12.187673"}, {id: "2", type: "stationSign", latitude: "55.647444", longtitude: "12.187545"}]
Unfortunately an error occurs when I am JSON.parse(), probably because of the objects in the string...
How do i convert a JSON string with objects to an array with objects?
JSON format requires that your keys also must be wrapped into "".
var string = '[{"id": "1", "type": "railroadCrossingSign", "latitude": "55.647432", "longtitude": "12.187673"}, {"id": "2", "type": "stationSign", "latitude": "55.647444", "longtitude": "12.187545"}]';
var arr = JSON.parse(string);
console.log(arr);
In order to achieve what you want. Your JSON key value pair must in a string format too.
Say,
var obj = '[{
"key" : "value"
}]';
Finally, when you use:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
You get the following results:
John, 30
Some observations :
First make sure your JSON should be a valid JSON.
Object properties should be wrapped into quotes "".
If your JSON is already an JSON Object then no need to parse it again otherwise it will throw an error.
var jsonObj = [{
"id": "1",
"type": "railroadCrossingSign",
"latitude": "55.647432",
"longtitude": "12.187673"
}, {
"id": "2",
"type": "stationSign",
"latitude": "55.647444",
"longtitude": "12.187545"
}];
var newObj = JSON.parse(jsonObj);
console.log(newObj); // Error : Uncaught SyntaxError: Unexpected token o in JSON at position 1

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"]);

Categories

Resources