Element from JSON - javascript

I have the next JSON object but I can't get latitude and longitude from it. In JavaScript every time I try I get undefined error:
{
"response": {
"date_ts": 1352514978,
"raw": {
"profile": "realtime",
"battery": -100,
"battery_state": "unknown"
},
"uuid": "b191d0d4-a967-47c9-b58b-3b491c8247db",
"location": {
"position": {
"altitude": 0,
"speed": -4,
"horizontal_accuracy": 5,
"latitude": 37.785834,
"longitude": -122.406417,
"heading": 0,
"vertical_accuracy": 0
},
"type": "point"
},
"date": "2012-11-09T20:36:18-06:00"
},
"type": "onSuccess",
"source": {}
}
Any advice?

You need to parse the JSON before you can manipulate it as a complex object structure.
var parsed = JSON.parse(myjson);
console.log(parsed.response.location.position.longitude);
DEMO: http://jsfiddle.net/VwWvP/

Related

how can i fetch data stats value

i have json file in an api source, The json output is as below.
{
"data": {
"metadata": { },
"segments": [
{
"type": "overview",
"attributes": {},
"expiryDate": "2021-07-03T00:25:07.8647619+00:00",
"stats": {
"timePlayed": {
"rank": null,
"percentile": 93,
"displayName": "Time Played",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 6635877,
"displayValue": "1,843h 17m",
"displayType": "TimeSeconds"
},
"score": {
"rank": null,
"percentile": 85,
"displayName": "Score",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 210790,
"displayValue": "210,790",
"displayType": "Number"
}
}
}
],
"availableSegments": [],
"expiryDate": "2021-07-03T00:25:07.8647619+00:00"
}
}
I want to get the data > segments > stats values ​​in this json output using fetch method. My Codes;
fetch(csgo2, {"headers": {"TRN-Api-Key": "xxxxxxxxxxxxxxxxxxxxxxxxx"}}).then(res => res.json()).then(body => {
const { timePlayed, score} = body.data.segments[0];
console.log(timePlayed.value)//undefined always output console.
})
I'm trying to get the data > segments > score or timesplayed value as in the code block, but I keep getting the undefined error from the console.
what i want to do is get the score or timesplayed value
The issue is you should use body.data.segments[0].stats. The body is an object with a data property, not the data property itself.

Changing the value of a field of an object in couchdb map function

In the map function of my view I am trying to change a field of a javascript object. Interestingly i can not change a field and than emit that object.
I expect all the name fields if the irem object would be "test". But i can`t change it. Any help would be great..
Map Function
function(doc) {
doc.movieList.forEach(function(item){
item.name = "test";
emit([doc.companyId,item.movieID],item);
});
}
Result
"rows": [
{
"key": [
"147",
"044a30f24e98660a8a8c12d09b1cafb3"
],
"value": {
"categoryID": 4,
"dataModelVersion": 1,
"forSale": false,
"movieID": "044a30f24e98660a8a8c12d09b1cafb3",
"name": "HULK", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
{
"key": [
"147",
"07c3c1bc4ac5d99286ccc54cde06b86a"
],
"value": {
"categoryID": 2,
"dataModelVersion": 1,
"forSale": false,
"movieID": "07c3c1bc4ac5d99286ccc54cde06b86a",
"name": "KACIS-PLANI", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
{
"key": [
"147",
"0c6f28034e39bc94009be0375e2fba2a"
],
"value": {
"categoryID": 8,
"dataModelVersion": 1,
"forSale": false,
"movieID": "0c6f28034e39bc94009be0375e2fba2a",
"name": "YOLA-GELDIK", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
Checking into CouchDB code, the doc provided to the map function is sealed so no modification is allowed over the original object.
You need to copy the original object into a new one in order to modify its attributes.

How do I console.log one value of this JSON Object?

I am new to javascript and to JSON, so please forgive me.
If I have the following JSON Object, how would I console.log() out the value of autonum?
{
"database": "testdb",
"table": "path",
"affectedColumns": [
{
"name": "autonum",
"charset": null,
"type": 8
},
{
"name": "TimeStamp",
"charset": null,
"type": 18,
"metadata": {
"decimals": 0
}
},
{
"name": "FilePath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirPath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "EventName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileExt",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 10
}
},
{
"name": "FileSize",
"charset": null,
"type": 3
},
{
"name": "MainFlag",
"charset": null,
"type": 1
},
{
"name": "DeleteFlag",
"charset": null,
"type": 1
},
{
"name": "Status",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 255
}
},
{
"name": "ProcessedFlag",
"charset": null,
"type": 1
}
],
"changedColumns": [],
"fields": {
"autonum": 121,
"TimeStamp": "2016-01-13T00:21:13.000Z",
"FilePath": "c:/1E0304F120151223030158001.mp4",
"DirPath": "c:\\",
"DirName": null,
"EventName": null,
"FileName": "1E0304F120151223030158001.mp4",
"FileExt": ".mp4",
"FileSize": 2218108,
"MainFlag": 0,
"DeleteFlag": 0,
"Status": null,
"ProcessedFlag": 0
}
}
Depending on which autonum you want, and assuming your variable storing the JSON is data, you'll want to do something as follows:
console.log(data.fields.autonum);
or
console.log(data.affectedColumns[0].name);
You'd use the following code, assuming the json object is called record:
console.log(record.fields.autonum);
You have two main ways of doing it. Both are correct ways. Lets say your object is named obj. Use console.log as following:
console.log(obj.fields.autonum)
console.log(obj['fields']['autonum'])
First case is easier as compare to second case.
Second case is safer as it will allow you to even take care of keys which have spaces e.g.
var my_other_object = {
'Santa Clara': 'USA',
'Toronto': 'Canada'
};
console.log(my_other_object['Santa Clara']) // Output will be 'USA'
For your understanding, in above object 'Santa Clara' and 'Toronto' are called 'keys' of my_other_object and 'USA', 'Canada' are called 'values' of those 'keys'.
So JSON object is essentially combination of key:value pairs.
P.S. Never apologize while asking a question all questions are valid but it is good to always search before asking. Still, people are always happy to help here. We all have went through same phases. :)
Lets say your object name var data, then data.fields.autonum would give us value 121
console.log(data.fields.autonum)
Just FYI:
As it is stated on MDN website:
some JavaScript is not JSON, and some JSON is not JavaScript
Just in order to improve understanding of vocabulary, 'JSON Object' is not a thing in our context ... it is
a syntax for serializing objects

JavaScript GeoJson Parser

i have geojson data:
{
"type":"FeatureCollection",
"metadata":{
"generated":1417015873000,
11-26T14:33:40&endtime=2014-11-26T14:33:45",
"title":"USGS Earthquakes",
"status":200,
"api":"1.0.13",
"count":1
},
"features":
[{
"type":"Feature",
"properties":
{
"mag":6.8,
"place":"160km NW of Kota Ternate, Indonesia",
"time":1417012423350,"updated":1417015584000,
"tz":480,
"url":"http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail":"http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt":1,
"cdi":5,
"mmi":4.98,
"alert":"green",
"status":"reviewed",
"tsunami":1,
"sig":712,
"net":"us",
"code":"b000t08w",
"ids":",at00nfnhsd,pt14330000,usb000t08w,",
"sources":",at,pt,us,",
"types":",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst":null,
"dmin":1.45,
"rms":1.32,
"gap":37,
"magType":"mwb",
"type":"earthquake",
"title":"M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry":{"type":"Point","coordinates":[126.5456,1.9752,41.06]},
"id":"usb000t08w"
}]
}
how to parse value "title" ?
var geojson = JSON.parse(geojson_data);
Turns the geojson string into an object, from there you can get whatever you values you want from it.
Edit: your json is invalid, where are you getting the data from? I cleaned it up, so you can call JSON.parse on it. However, it is not valid geojson, so I'd double check where you come up with the data. This geojson validator might help.
{
"metadata": {
"generated": 1417015873000,
"11-26T14: 33: 40&endtime=2014-11-26T14: 33": 45,
"title": "USGSEarthquakes",
"status": 200,
"api": "1.0.13",
"count": 1
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 6.8,
"place": "160km NW of Kota Ternate, Indonesia",
"time": 1417012423350,
"updated": 1417015584000,
"tz": 480,
"url": "http://comcat.cr.usgs.gov/earthquakes/eventpage/usb000t08w",
"detail": "http://comcat.cr.usgs.gov/fdsnws/event/1/query?eventid=usb000t08w&format=geojson",
"felt": 1,
"cdi": 5,
"mmi": 4.98,
"alert": "green",
"status": "reviewed",
"tsunami": 1,
"sig": 712,
"net": "us",
"code": "b000t08w",
"ids": ",at00nfnhsd,pt14330000,usb000t08w,",
"sources": ",at,pt,us,",
"types": ",cap,dyfi,general-link,geoserve,impact-link,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,",
"nst": null,
"dmin": 1.45,
"rms": 1.32,
"gap": 37,
"magType": "mwb",
"type": "earthquake",
"title": "M 6.8 - 160km NW of Kota Ternate, Indonesia"
},
"geometry": {
"type": "Point",
"coordinates": [
126.5456,
1.9752,
41.06
]
},
"id": "usb000t08w"
}
]
}

How to select object in muti level array

I am attempting to get just the smiling array under tags then attributes. I have tried both to search and simply select. Every attempt results in an undefined variable. If you could explain how to select the smiling array that would be excellent!
{
"status": "success",
"photos": [{
"url": "http://tinyurl.com/673cksr",
"pid": "F#019cbdb135cff0880096136c4a0b9bad_3547b9aba738e",
"width": 375,
"height": 406,
"tags": [{
"uids": [],
"label": null,
"confirmed": false,
"manual": false,
"width": 30.67,
"height": 28.33,
"yaw": -16,
"roll": -1,
"pitch": 0,
"attributes": {
"face": {
"value": "true",
"confidence": 84
},
"smiling": {
"value": "false",
"confidence": 46
}
},
"points": null,
"similarities": null,
"tid": "TEMP_F#019cbdb135cff0880096136c00d500a7_3547b9aba738e_56.80_41.13_0_1",
"recognizable": true,
"center": {
"x": 56.8,
"y": 41.13
},
"eye_left": {
"x": 66.67,
"y": 35.71,
"confidence": 51,
"id": 449
},
"eye_right": {
"x": 50.67,
"y": 35.47,
"confidence": 57,
"id": 450
},
"mouth_center": {
"x": 60.8,
"y": 51.23,
"confidence": 53,
"id": 615
},
"nose": {
"x": 62.4,
"y": 42.61,
"confidence": 54,
"id": 403
}
}]
}],
"usage": {
"used": 21,
"remaining": 79,
"limit": 100,
"reset_time": 1390111833,
"reset_time_text": "Sun, 19 January 2014 06:10:33 +0000"
},
"operation_id": "edc2f994cd8c4f45b3bc5632fdb27824"
}
This particular code, will aggregate all the smiling attribute from the given object and return that as an Array.
map function will get smiling attribute from each and every tag
concat function will flatten all the attributes and returns a single array per photo.
reduce function will gather all the attributes all the photos and accumulate the result in result and that will be returned at the end.
var result = data.photos.reduce(function(result, currentPhoto) {
return result.concat(currentPhoto.tags.map(function(currentTag) {
return currentTag.attributes.smiling;
}));
}, []);
console.log(result);
Output
[ { value: 'false', confidence: 46 } ]
JSON.parse(json).photos[0].tags[0].attributes.smiling
obj.photos[0].tags[0].attributes.smiling
The best way would be to loop through the tags, instead of hardcoding 0 in there
obj.photos.forEach(function(photo){
photo.tags.forEach(function(tag){
tag.attributes.smiling; // here it is
});
});
It's a bit tricky since your JSON object is a mixture of objects and arrays, but here's how you would get to the "smiling" object (it's an object since there's no associative arrays in JavaScript):
var smiling_object = obj["photos"][0]["tags"][0]["attributes"]["smiling"];
Then you if you want to do something with it:
var some_var = smiling_object["value"];
var some_other_var = smiling_object["confidence"];
alert("The combined string is " + some_var + " and " + some_other_var);

Categories