jQuery and Json push issue - json

I am okay with using push({}) to create my javascript array, however one of my fields has a list of its own. So I'm having trouble doing the push() on level down.
As follows, tradeDetails array is defined and the EXTENSIONS field has a collection of values. How do I handle this one below.
function TradeDetailsToJson(xml) {
var tradeDetails = [];
var tradeId = $(xml).find("tradeHeader tradeId").text();
var tradeDate = $(xml).find("tradeHeader tradeDate").text();
var tradeType = $(xml).find("tradeHeader tradeType").text();
var counterparty = $(xml).find("tradeHeader counterparty").text();
var internalUnit = $(xml).find("tradeHeader internalUnit").text();
var buySell = $(xml).find("tradeHeader buySell").text();
var status = $(xml).find("tradeHeader status").text();
tradeDetails.push({
"tradeId": tradeId,
"tradeDate": tradeDate,
"tradeType": tradeType,
"counterparty": counterparty,
"internalUnit": internalUnit,
"buySell": buySell,
"status": status,
"**extensions**":[]
});
// NOW I'D LIKE TO PUSH MY EXTENSIONS !!
var extName = ""
var extValue = "";
$(xml).find("extensions extension").each(function () {
extName = $(this).find("name").text();
extValue = $(this).find("value").text();
//tradeDetails[extensions].push({ "name": name, "value": value }); ??????
});
}
thank you in advanced.
Bob

Use push on the extensions property again?
tradeDetails.push({
"tradeId": tradeId,
"tradeDate": tradeDate,
"tradeType": tradeType,
"counterparty": counterparty,
"internalUnit": internalUnit,
"buySell": buySell,
"status": status,
"extensions":[]
});
tradeDetails.extensions.push({ "name": name, "value": value });
With what you have tried, you need to wrap extensions which is the key of the object tradeDetails, in quotes.
So change
tradeDetails[extensions].push({ "name": name, "value": value });
to
tradeDetails["extensions"].push({ "name": name, "value": value });

Related

My Indexeddb only creates the object store name but does not show the data i have added; how can i fix this?

So after the transaction is created, it is where it goes wrong as when I inspect the indexed db on mozzila firefox (it doesnt show at all on google chrome). It will only show the object store but not the data that was suppose to added ( John and Francis) any advice would be great. thank you.
// This works on all devices/browsers, and uses IndexedDBShim as a final fallback
var indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
// Open (or create) the database
var open = indexedDB.open("jokes", 1);
// Create the schema
open.onupgradeneeded = function() {
var db = open.result;
var store = db.createObjectStore("MyObjectStore", {keyPath: "id"});
var index = store.createIndex("NameIndex", ["name.last", "name.first"]);
}
open.onsuccess = function() {
// Start a new transaction
var db = open.result;
var tx = db.transaction("MyObjectStore", "readwrite");
var store = tx.objectStore("MyObjectStore");
var index = store.index("NameIndex");
// Add some data
store.put({id: 1, name: {first: "John", last: "Mercury"}, country: France});
store.put ({id: 2, name: {first: "Francis", last: "Perez"}, country: Spain});
// Query the data
var getJohn = store.get(1);
var getFrancis = index.get(["Perez", "Francis"]);
getJohn.onsuccess = function() {
console.log(getJohn.result.name.first); // => "John"
};
getFrancis.onsuccess = function() {
console.log(getFrancis.result.name.first); // => "Francis"
};
// Close the db when the transaction is done
tx.oncomplete = function() {
db.close();
};
}
here are some issue that i could find. Fixing them fixed the issue.
In the lines where you are putting data into the Indexed DB, you gotta use quotes for country name.
store.put({id: 1, name: {first: "John", last: "Mercury"}, country: "France"});
Secondly, all IndexedDB operations are async, so you gotta wait for success of the put operation before you can fetch.
let putOp = store.put({id: 1, name: {first: "John", last: "Mercury"}, country: 'France'});
putOp.onsuccess = function() { // Fetch records here }

How to set one more level in Object of a not predefined item?

The main issue is the following:
Get JSON from the server
Put data to form
Serialize form
Create JSON with correct structure
Send it to the server
I have difficulties on the fourth step, what I've done:
methods: {
onSubmit: function() {
var dataForm = new FormData(this.$refs['form']);
var data = [];
for (var _iterator = dataForm.entries(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _Object$assign;
var _Helper = {};
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _ref2 = _ref,
key = _ref2[0],
val = _ref2[1];
Object.assign(_Helper, (_Object$assign = {}, _Object$assign[key] = val, _Object$assign));
}
}
},
Here you go - a link to the codepen.
As you can see I could create JSON like that:
{"0":"a","1":"b","2":"c","3":"d","4":"e","5":"d"}
However, I need smth like that:
{
"0": {
"text": "a"
},
"1": {
"text": "b"
},
"2": {
"text": "c"
},
"3": {
"text": "d"
},
"4": {
"text": "e"
},
"5": {
"text": "d"
}
}
What Can I do to implement it and also keep the correct structure of my JSON?
To change the format, change in the location it assigns the property value:
Object.assign(data, (_Object$assign = {}, _Object$assign[key] = {text: val}, _Object$assign));
// -------------------------------------------------------------^^^^^^^^^^^
Instead of a string (val), assign the object in the format you want ({text: val}).
Updated CodePen.
If you can use modern (ES6) JavaScript, there's a much shorter notation for that:
var [key, val] = _ref;
Object.assign(data, {[key]: {text: val}});
CodePen here.
Or (because you are using FormData#entries() you do are using modern JS):
var formData = Array.from(new FormData(this.$refs['form']).entries());
var data = Object.assign(...formData.map(([key, val]) => ({[key]: {text: val}})));
console.log(JSON.stringify(data));
Targetting IE10 and above
To target IE10 and above you'll need polyfills. The problem is not the syntax, but the absence of functions like .entries(), that will be added by the polyfills. To use the least amount possible of polyfills, you'll have to iterate the iterator "manually" (kind of like you are already). For more info, check this answer.
You can do the whole construction much more simply:
onSubmit: function () {
const dataForm = new FormData(this.$refs['form']);
const data = {};
for (const i of dataForm.entries()) {
data[i[0]] = { text: i[1] }
}
console.log(JSON.stringify(data));
}

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

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

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.

actionscript 3 JSON failed to parse data

I have received a JSON data like this:
'{"result":[[["test","test"],["test","test"]],[],[],[]]}'
OR
'{"result":[
[
["test","test"],
["test","test"]
],
[],
[],
[]
]
}'
But when I try to JSON.parse(data);, it is converted to object like this:
{[[["test","test"],["test","test"]],[],[],[]]:}
Is there anyway to fix it?
ADDITIONAL:
i have traced what happen before,during,after JSON do, and the problem seems to be the parse itself, sometime it work, some time doesn't
var object:Object = {test:[[["Test","test1"],["test2"]],["test3"],[],[]]}
var stringed:String = JSON.stringify(object);
trace(stringed)//{"test":[[["Test","test1"],["test2"]],["test3"],[],[]]}
var backed:Object = JSON.parse(stringed);
for each(var thigng:String in backed){
trace(thigng, "=", backed[thigng])//Test,test1,test2,test3,, = undefined
}
var object:Object = {"test":"test3"}
var stringed:String = JSON.stringify(object);
trace(stringed)//{test:"test3"}
var backed:Object = JSON.parse(stringed);
for each(var thigng:String in backed){
trace(thigng, "=", backed[thigng])//test3 = undefined
}
A "for each...in" loop will only give you the value not the key.
What you need is the for in loop.
As you can see from the example below where you went wrong
var object:Object = {"this_is_the_key":"VALUE"}
var stringed:String = JSON.stringify(object);
var backed:Object = JSON.parse(stringed);
for each(var thigng:String in backed){
trace('KEY:', thigng, ' VALUE:' ,backed[thigng]) // KEY: VALUE VALUE: undefined
}
trace('------')
for(thigng in backed){
trace('KEY:', thigng, ' VALUE:' ,backed[thigng]) //KEY: this_is_the_key VALUE: VALUE
}
Also this is not a valid JSON string
'{"result":[[["test","test"],["test","test"]],[],[],[]]}'