extract particular data from json file - javascript

I am new to using javascript as well as json. I need to extract certain sections from json for processing the data.
"response": {
"status": "OK",
"code": 200,
"header": [
{
"key": "Cache-Control",
"value": "no-cache"
},
{
"key": "Pragma",
"value": "no-cache"
},
"body": "{\r\n \"#odata.context\":\"http://localhost:53292/odata/$metadata#Movies\",\"value\":[\r\n {\r\n \"Id\":1,\"Title\":\"StarWars - The Force Awakens\",\"ReleaseDate\":\"2015-10-25T00:00:00+05:30\",\"Rating\":\"FiveStar\",\"Director\":{\r\n \"FirstName\":\"J.J.\",\"LastName\":\"Abrams\"\r\n },\"LastModifiedOn\":\"2016-09-30T10:46:33.3114027+05:30\"\r\n },{\r\n \"Id\":2,\"Title\":\"Mad Max - The Fury Road\",\"ReleaseDate\":\"2015-05-15T00:00:00+05:30\",\"Rating\":\"FourStar\",\"Director\":{\r\n \"FirstName\":\"George\",\"LastName\":\"Miller\"\r\n },\"LastModifiedOn\":\"2016-09-30T10:46:33.3114027+05:30\"\r\n }\r\n ]\r\n}",
"cookie": [],
"responseTime": 30,
"responseSize": 583,
"update": {},
"reason": {},
"text": {},
"json": {},
"mime": {},
"dataURI": {},
"size": {},
"describe": {},
"toObjectResolved": {},
"toJSON": {},
"meta": {}
},
"id": "5a3d3fb3-93a7-4555-b0d5-a4482d98b888"
}
This is my json file. I need only 'body' from it.How to get this done using javascript? Please help me.

var jsonParsed = JSON.parse( put_yourJSON_here );
and then just use jsonParsed.body

Youc an use JSON.parse to convert json data to javascript object and then get the data of body, try with below sample:
var data = JSON.parse("put your data here");
var body = data.body;

Provided that your JSON is a string and not just a general Javascript object, then you can access its properties by parsing it.
var jsonText = '{"id":"123", "name":"Joe Bloggs"}';
var jsonObj = JSON.parse(jsonText);
var name = jsonObj.name; // Joe Bloggs
Edit: Or you can get the resource using jQuery.getJSON():
$.getJSON( "path/to/file.json", function( data ) {
var name = data.name; // Joe Bloggs
});

Related

How do I access "order" in this JSON (with semicolons in the name)?

Vijay Anand asked this question yesterday, but it was closed before he got an answer:
HTTP Response:
{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}
Javascript code:
var json = response;
var order = json.object.entry.content['m:properties']['d:Order']; // I intend to read Order no from the below response.
Error (example, jsbin.com):
"TypeError: Cannot read property 'entry' of undefined
at null.js:27:25
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
Per JSLint, the response is valid JSON.
json.object.entry is obviously wrong ... but
Q: What is the correct Javascript syntax to access the "order" value (named d:Order), when m:properties and d:Order both have semicolons in the name?
PS: I nominated Vijay's original question for re-opening ... but I'm not optimistic. Hence my new question.
You need to parse the JSON. And there's no object property anywhere, it's jut json.entry.content.
response = `{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}`;
var json = JSON.parse(response);
var order = json.entry.content['m:properties']['d:Order'];
console.log(order);

How to convert JSON string having multiple rows to single row using javascript function

I have an output of REST API in following JSON format:
I need to convert the format to flat format so it can be passed as input to another API call.
{
"result": {
"data": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
},
// ... 1000's of rows like this
]
}
}
I need to convert it in below format using a java-script
Desired format:
{"result":{ "data":[{"id":"b3","dateTime":"2019-09- 10T11:32:05.220Z","DiagnosticAccelerationSideToSideId":0,"DiagnosticAccelerationForwardBrakingId ":2.824315071105957},...
The rows needs to be merged with primary key as combination of ID and dateTime attributes. Please note the diagnostic id value becomes key for the required format and data value is the value of the key.
Is there any way to convert this JSON to above flat format.
Need to convert JSON having many rows for single data entry to single row format. Need one java-script function that can accept a string of rows format and convert or merge it and return the string in desired format
function String mergeRows(String flatDataJSONString) {
...
}
If the items are ordered (meaning i and i+1 are merged) than iterate with jumps of i += 2;
If its not ordered or the amount of items to be merged can be > 2 you use an object with unique key composed of the id and date, and override its data whenever a record match this key:
function merger (jsonStr) {
// convert str to obj
const jsonObj = JSON.parse(jsonStr);
const dataObj = {};
for (let i = 0; i < jsonObj.result.length; i++) {
const item = jsonObj.result[i];
// use unique key to merge by
const itemUniqueKey = item.device.id + item.dateTime;
// take last value or create empty object if not exists
const existingItem = dataObj[itemUniqueKey] || {};
// add some logic to merge item with existingItem as you need
...
// set the result back to dataObj to be used on next merges
dataObj[itemUniqueKey] = [merge result of item and existing item];
}
// take dataObj values, you don't need the keys any more
const dataArr = Object.values(dataObj);
const finalResult = {
result: {
data: dataArr
}
}
// convert back to json
return JSON.stringify(finalResult);
}
As stated in the comment you want first to have a clean json definition in order to stringify it. Please get to the following definition of your JSON first:
const json = {
"result": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
}]
};
and then you will be able to perform like hereafter :
JSON.stringify(json)
Hope this helps !

Backbone .fetch() adds one too many models

I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.

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;

Mixed array with json - parsing issue

I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.

Categories

Resources