How to remove {"Result": in JSON string? - json

I have the following JSON result when calling an API, how can I convert the JSON string I have so I can just see the results:
var response = request_.responseText;
var obj = JSON.parse(request_.response);
var j = obj;
var js = JSON.stringify(j)
console.log(js)
JSON Output of var js:
{"Result":[{"PK_ID":1,"MedicationId":1,"NHS_Number":"123","Medication_Name":"Asprin","Read_Code":"XaaYI","Dose":"500mg","Date_Started":"02/06/2016","Date_Ended":"03/06/2016"},{"PK_ID":2,"MedicationId":2,"NHS_Number":"1234","Medication_Name":"Ibuprofen","Read_Code":"EtQWEl","Dose":"100mg","Date_Started":"03/02/2016","Date_Ended":"05/02/2016"}]}
How can I remove the {"Result": } code that is wrapped around my JSON?

Update from
var j = obj;
to
var j = obj.Result;
var obj = {
"Result": [{
"PK_ID": 1,
"MedicationId": 1,
"NHS_Number": "123",
"Medication_Name": "Asprin",
"Read_Code": "XaaYI",
"Dose": "500mg",
"Date_Started": "02/06/2016",
"Date_Ended": "03/06/2016"
}, {
"PK_ID": 2,
"MedicationId": 2,
"NHS_Number": "1234",
"Medication_Name": "Ibuprofen",
"Read_Code": "EtQWEl",
"Dose": "100mg",
"Date_Started": "03/02/2016",
"Date_Ended": "05/02/2016"
}]
};
var j = obj.Result;
var js = JSON.stringify(j);
console.log(js);

Related

JSON: Keys and Field Names: Dynamically Parse

I have a JSON string
{"key": "2021-01-01 22:59:59", "data": {"field1": "newvalue1", "field2": "newvalue2"}}
I have to morph this json into the following:
{
"field1": {"before": "oldValue1", "new": "newvalue1"},
"field2": {"before": "oldValue2", "new": "newvalue2"}
}
The problem is that field1 and field2 are not always present. THe original JSON is dynamically generated by a DevExtreme DataGrid's Updates to a row. This is how far I got:
EDIT:
The below code works
var outputJSON = {};
var changes = {"field1": "newvalue1", "field2": "newvalue2"};
for(var i = 0; i < Object.keys(changes).length; i++){
var keyName = Object.keys(changes)[i];
outputJSON[keyName] = {};
outputJSON[keyName]["before"] = Object.values(changes)[0];
outputJSON[keyName]["after"] = Object.values(changes)[1];
}
console.log(JSON.stringify(outputJSON));
I think this is closer to what I need.
Working code:
var keys = Object.keys(JSON.stringify(changes));
for (var i = 0; i < Object.keys(changes).length; i++) {
var fieldName = Object.keys(changes)[i];
inputJSON[fieldName] = {};
inputJSON[fieldName]["before"] = editRow[fieldName];
inputJSON[fieldName]["after"] = (changes)[fieldName];
}

Getting values from JSON using appscript

I'm creating two-dimentional array with google appscript using chrome devices users with the JSON response from a directory. I've been able to get values. However, when I try to get recentUsers represented as:
{
"kind": "directory#chromeosdevices",
"chromeosdevices": [
{
"kind": "directory#chromeosdevice",
"etag": "1234567890"
"deviceId": "def456",
"serialNumber": "234567",
"status": "ACTIVE",
"lastSync": "2013-03-05T17:30:04.325Z",
"supportEndDate": "2014-04-05T17:30:04.325Z",
"annotatedUser": "help desk",
"annotatedLocation": "Mountain View help desk Chromebook",
"annotatedAssetId": "1234567890",
"notes": "Loaned from support",
"orderNumber": "1234",
"willAutoRenew": true,
"osVersion": "Browser Version 18.0",
"platformVersion": "Platform Version 1415.2.0",
"firmwareVersion": "Firmware Version 1.2.3.4",
"bootMode": "validated",
"lastEnrollmentTime": "2012-04-05T17:30:04.325Z",
"orgUnitPath": "corp/engineering",
"recentUsers": [
{
"type": "USER_TYPE_MANAGED",
"email": "user#customer.com" //I'm trying to get the most recent user's email
}
],
"activeTimeRanges": [
{
"date": "2012-04-05",
"activeTime": "3600000"
}
],
}
],
"nextPageToken": "abcdefghijkl123"
}
I get an array but I can't get the value. I'm trying to get the most recent user's email. Anyone have experience with appscript? I've tried recentUsers[0].email and recentUser[0]['email']. This is the code I have to far: //I commented where I'm trying to push a value
enter code here
var chromeArgs = {
maxResults: 200,
orderBy: 'annotatedUser',
projection: "FULL"
};
var getChromes = (AdminDirectory.Chromeosdevices.list('XXXXXXXXX', chromeArgs));
var chromes = getChromes.chromeosdevices;
if (chromes && chromes.length > 0) {
Logger.log('Devices:');
//2d array
var wholeValues = [];
for (var i = 0; i < chromes.length; i++){
//create a 1D array first with pushing 0,1,2 elements with a for loop
var value = [];
for (var j = 0; j < 1; j++) {
var chrms = chromes[i];
var recentUser = chrms.recentUsers;
value.push(recentUser[0].email); // Here is where I need help
}
//pushing the value array with [0,1,2] to thw wholeValues array.
wholeValues.push(value);
} // the outer for loop runs five times , so five the 0,1,2 with be pushed in to thewholevalues array by creating wholeValues[0][0],wholeValues[0][1]...till..wholeValues[4][2]
Logger.log(wholeValues); '''
You are very close, the only thing you need to change is to replace the static recentUsers[0] with dynamic recentUsers[j] within the loop
Sample:
function getChromes(){
var chromeArgs = {
maxResults: 200,
orderBy: 'annotatedUser',
projection: "FULL"
};
var getChromes = (AdminDirectory.Chromeosdevices.list('XXXXXXXXX', chromeArgs));
var chromes = getChromes.chromeosdevices;
if (chromes && chromes.length > 0) {
Logger.log('Devices:');
var wholeValues = [];
for (var i = 0; i < chromes.length; i++){
var chrms = chromes[i];
var recentUser = chrms.recentUsers;
var value = [];
for (var j = 0; j < recentUser.length; j++) {
Logger.log(recentUser[j].email);
value.push(recentUser[j].email);
}
wholeValues.push(value);
}
Logger.log(wholeValues);
}
}
Note that you need to specify the iteration limit of the inner loop dynamically j < recentUser.length; instead of j < 1 to account for different quantity of recent users for each chrome device.

Angular 2, split data from Json

Hi I have a json from http request, the server json response is this:
{
"map": {
"03/04": 13,
"05/04": 41,
"06/04": 1,
"12/04": 4,
"14/04": 7,
"18/04": 8,
"19/04": 2,
"22/04": 1,
"25/04": 4
},
"links": []
}
I want to split dates in 1 array and values in other array,
At the end I want :
Data[03/04,05/04,06/04....] and
Val[13,41,1....]
is it possible without difficult implementation?
This could be an approach:
private Data = [];
private Val = [];
for (let key in data) {
this.Data.push(key);
this.Val.push(data[key])
}
let date = Object.keys(JsonRespond.map) // get all keys in map object
let value = [];
date.forEach((key) => {
value.push(JsonRespond.map[key]);
})
you can use this
var a=`{
"map": {
"03/04": 13,
"05/04": 41,
"06/04": 1,
"12/04": 4,
"14/04": 7,
"18/04": 8,
"19/04": 2,
"22/04": 1,
"25/04": 4
},
"links": []
}`
var Data=[];
var val=[]
for(each in a.map){
Data.push(each);
val.push(a.map[each]);
}
Use Object.entries
var dates = [];
var values = [];
var data = Object.entries(yourObj.map);
for (var i in data.length) {
dates.push(data[i][0]);
values.push(data[i][1]);
}

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

Selecting a specific node in JSON using Appcelerator Titanium

Hopefully an easy question for you.
I have an API service from Rackspace which I call, recently they changed the order of some of the responses, meaning part of my app would no longer upload images to the correct POST url.
I've put a temp fix in place by hard coding the URL's it should be posting to, but I want to be sure I future proof against any changes in their API ordering or indeed any changes to the URL itself.
So, originally I was using the JSON response and choosing the first node and its children.
var CFtenantID = getRSToken.access.serviceCatalog[0].endpoints[0].tenantId;
var CFregion = getRSToken.access.serviceCatalog[0].endpoints[0].region;
var CFpublicURL = getRSToken.access.serviceCatalog[0].endpoints[0].publicURL;
Now, that node has moved to position 18 in a long list. So, I can manually set the script to retrieve it.
var CFtenantID = getRSToken.access.serviceCatalog[17].endpoints[0].tenantId;
var CFregion = getRSToken.access.serviceCatalog[17].endpoints[0].region;
var CFpublicURL = getRSToken.access.serviceCatalog[17].endpoints[0].publicURL;
What I'd like to be able to do, is scan for the "name" instead and just return the CloudFiles info I need, rather than having to declare an actual number of the array.
Here is a snippet of the JSON response from Rackspace.
{
"name": "cloudFeeds",
"endpoints": [
{
"region": "LON",
"tenantId": "1234",
"publicURL": "https://lon.feeds.api.rackspacecloud.com/1234",
"internalURL": "https://atom.prod.lon3.us.ci.rackspace.net/1234"
}
],
"type": "rax:feeds"
},
{
"name": "cloudFiles",
"endpoints": [
{
"region": "LON",
"tenantId": "MossoCloudFS_xxxxxx",
"publicURL": "https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_xxxxx",
"internalURL": "https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_xxxxx"
}
],
"type": "object-store"
},
{
"name": "cloudFilesCDN",
"endpoints": [
{
"region": "LON",
"tenantId": "MossoCloudFS_xxxxxx",
"publicURL": "https://cdn3.clouddrive.com/v1/MossoCloudFS_xxxxxx"
}
],
"type": "rax:object-cdn"
}
And here is my overall script in Appcelerator.
var authCloudFiles = Ti.Network.createHTTPClient({
onload: function() {
// output
Ti.API.info(this.responseText);
var getRSToken = JSON.parse(this.responseText);
var rsToken = getRSToken.access.token.id;
var rsTenantID = getRSToken.access.token.tenant.id;
var rsTenantName = getRSToken.access.token.tenant.name;
var CFtenantID = getRSToken.access.serviceCatalog[17].endpoints[0].tenantId;
var CFregion = getRSToken.access.serviceCatalog[17].endpoints[0].region;
var CFpublicURL = getRSToken.access.serviceCatalog[17].endpoints[0].publicURL;
var rsUserID = getRSToken.access.user.id;
Ti.App.Properties.setString('rsToken', rsToken);
Ti.App.Properties.setString('rsTenantID', rsTenantID);
Ti.App.Properties.setString('rsTenantName', rsTenantName);
Ti.App.Properties.setString('CFtenantID', CFtenantID);
Ti.App.Properties.setString('CFregion', CFregion);
Ti.App.Properties.setString('CFpublicURL', CFpublicURL);
Ti.App.Properties.setString('rsUserID', rsUserID);
//alert(rsToken);
Ti.API.info('rsToken: ' + rsToken);
Ti.API.info('rsTenantID: ' + rsTenantID);
Ti.API.info('rsTenantName: ' + rsTenantName);
Ti.API.info('CFtenantID: ' + CFtenantID);
Ti.API.info('CFregion: ' + CFregion);
Ti.API.info('CFpublicURL: ' + CFpublicURL);
Ti.API.info('rsUserID: ' + rsUserID);
// then we need to load the next step
rackspaceUpload();
}
});
authCloudFiles.open('POST', 'https://identity.api.rackspacecloud.com/v2.0/tokens');
Can anyone help?
Simon
I have never used Appcelerator Titanium before, but it looks like it is just JavaScript.
You could try replacing the following:
var CFtenantID = getRSToken.access.serviceCatalog[17].endpoints[0].tenantId;
var CFregion = getRSToken.access.serviceCatalog[17].endpoints[0].region;
var CFpublicURL = getRSToken.access.serviceCatalog[17].endpoints[0].publicURL;
with:
var CFtenantID = "";
var CFregion = "";
var CFpublicURL = "";
var catalog = getRSToken.access.serviceCatalog;
for (var i=0; i<catalog.length; i++) {
if (catalog[i].name == "cloudFiles") {
for (var j=0; i<catalog[i].endpoints.length; j++) {
if (catalog[i].endpoints[j].region == "LON") {
CFtenantID = catalog[i].endpoints[j].tenantId;
CFregion = catalog[i].endpoints[j].region;
CFpublicURL = catalog[i].endpoints[j].publicURL;
break;
}
}
}
}
My JavaScript is a little rusty though, you may want to add some additional error handling.