Appcelerator - Converting circular structure to JSON - json

I have a problem with converting a JSON in string. On iOS all works perfect but on Android I have this error:
[ERROR] : TiExceptionHandler: (main) [2,20592] - Message: Uncaught TypeError: Converting circular structure to JSON
This is my code:
var args = $.args
var data = args.data;
var oferta = data.oferta;
var params = data.params;
var parent = args.parent;
//INSERT
var producto = Alloy.createModel('Producto', {
oferta_id: parseInt(oferta.id),
data: JSON.stringify(args) //ERROR
});
The args passed to the controller are like this:
var args = {
data:
{
oferta: {id: 5},
params:{id_opcion_precio: 3445}
},
parent: {}
}
What's wrong?? Why on iOS works fine???

Not sure why you want to stringify args. Try to use JSON.stringify(args.data) when you create the model.
I guess you would have the same problem just stringify'ing args in a log statement like: console.log(JSON.stringify(args))?
I have run into similar problems when trying to write the entire event (e.g. from ti.map) to the console. Something makes it break - I assume there is added some attributes to the data that you don't see.

Finally I solved my problem doing this:
JSON.stringify({data: data, parent: parent});
This works I don't know why, but works

Related

NodeJS websocket access second layer JSON Data

const WebSocket = require('ws');
const ws = new WebSocket('wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD');
ws.on('message', function incoming(a) {
p=JSON.parse(a)
console.log(Object.keys(p));
console.log(p.data);
});
code can be tried here - npm.runkit.com/ws
I am trying to access the subparameters of the JSON object like bidprice and ask price. However unable to go beyond the data level. Have tried using data[0].bidprice,data.bidprice but nothing works.
Not sure if p.data is returning a str instead of a JSON.
Sample data is as follows
{ table: 'instrument',
action: 'update',
data:
[ { symbol: 'XBTUSD',
lastPrice: 6686,
lastTickDirection: 'MinusTick',
lastChangePcnt: 0.0053,
timestamp: '2018-09-23T15:04:18.946Z' } ] }
if output is stored as var a, a.data works but a.data.symbol or a.data[0].symbol doesnt work

Google script null object - don't understand why

I'm starting to write Google scripts to automatize certain tasks, and here I'm stuck on a problem I can't figure out by myself. I must say I'm neither an expert in app scripts (yet) nor in javascript.
Here is my problem. I make a call to a (private) REST API to retrieve some data. I get the result, parse it to get a Json object. Then I want to write some properties in a spreadsheet. For some reason, I can't get to manipulate nested objects.
Say I have a list of this json payload :
{
id: 2146904633,
status: "in_progress",
success_probability: 99,
amount: "0.0",
decision_maker: "Bob Mauranne",
business_contact: {
id: 2142664162,
nickname: "NIL",
}
}
EDIT : I made a mistake with the code I pasted (businessContact was not declared, instead a variable bc was declared).Thanks for the comment :) The code below is correct now, but still doesn't work.
I get it like with this (overly simplified) code :
var response = UrlFetchApp.fetch(url);
var dataAll = JSON.parse(response.getContentText());
var data, businessContact;
for (i = 0; i < dataAll.length; i++) {
data = dataAll[i];
businessContact = data.business_contact;
Logger.log(data.status);
Logger.log(businessContact);
Logger.log(businessContact.id);
}
My problem is that when I call businessContact.id I get the error "TypeError: unable to read property id from null object". And I don't understand since I can see the content from businessContact : either from the log call or from the debugger, it's definately not null.
It seems to happen only on nested objects, because on simple properties, I don't have any error. And I have the same problems on all nested objects, whatever json payload I've tried so far...
I searched on the internet for a solution but found none. It probably is very basic, but I can't get it to work.
Any idea ?
You never define "businessContact" that your using in the logger. You define "bc" but not "businessContact". If you changed it to Logger.log(bc.id) it should work.
Here is a trimmed down version of what your trying to do also.
function getJSON() {
var url = "your url";
var response = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(response)
data.forEach(function(item) {
Logger.log(item.business_contact.id)
})
}
Heres an example pulling weather data.
function myFunction() {
var url = "https://www.aviationweather.gov/gis/scripts/TafJSON.php";
var response = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(response)
data.features.forEach(function(feature) {
Logger.log(feature.properties.id)
})
}
I finally found the solution. This code is in a loop, sometimes the object business_contact is null and I hadn't seen it :|
Clearly I should stop working late in the evening when I learn a new technology ...
My bad, sorry for the noise, and thanks for the answers and comments guys.

$resource : $save does not work

I have a json file called data.json containing some data:
[
{
"name" : "toto"
}
]
And the script I wrote to manage it :
var Data = $resource("data.json", {},
{
query: {method:'GET',isArray:true}
});
var data = Data.query(function()
{
var d = data[0];
d.name = "Titi";
d.$save();
});
Everything work before I call $save() on my object. I have this error:
[11:30:24.962] "Error: [$resource:badcfg] Error in resource configuration.
Expected response to contain an object but got an array
I don't really know the problem. I have already read many examples and documentations but this does not seem clearer to me.
Just guessing to help quickly here... You may have several issues, var d = data[0]. data should be from an argument/parameter of the function not the var data which is null until the return result from Data.query changes it. $save should also likely be on the $resource object, not the object in the array. Not an angular person, but guessing that might be the case.

how to send the data in Json structure

I have a rest service for which I am sending the Json data as ["1","2","3"](list of strings) which is working fine in firefox rest client plugin, but while sending the data in application the structure is {"0":"1","1":"2","2":"3"} format, and I am not able to pass the data, how to convert the {"0":"1","1":"2","2":"3"} to ["1","2","3"] so that I can send the data through application, any help would be greatly appreciated.
If the format of the json is { "index" : "value" }, is what I'm seeing in {"0":"1","1":"2","2":"3"}, then we can take advantage of that information and you can do this:
var myObj = {"0":"1","1":"2","2":"3"};
var convertToList = function(object) {
var i = 0;
var list = [];
while(object.hasOwnProperty(i)) { // check if value exists for index i
list.push(object[i]); // add value into list
i++; // increment index
}
return list;
};
var result = convertToList(myObj); // result: ["1", "2", "3"]
See fiddle: http://jsfiddle.net/amyamy86/NzudC/
Use a fake index to "iterate" through the list. Keep in mind that this won't work if there is a break in the indices, can't be this: {"0":"1","2":"3"}
You need to parse out the json back into a javascript object. There are parsing tools in the later iterations of dojo as one of the other contributors already pointed out, however most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is:
var str = your_incoming_json_string,
// here is the line ...
obj = JSON.parse(string);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
For the browsers that don't support JSON.parse() you can implement it using json2.js, but since you are actually using dojo, then dojo.fromJson() is your way to go. Dojo takes care of browser independence for you.
var str = your_incoming_json_string,
// here is the line ...
obj = dojo.fromJson(str);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
If you're using an AMD version of Dojo then you will need to go back to the Dojo documentation and look at dojo/_base/json examples on the dojo.fromJson page.

Node.js: Extend JSON object

I would like to extend the native JSON object of node.js. In my example, I was able to extend it to add a merge(json1, json2) function, which merges 2 JSONs:
JSON.merge = function(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function (source) {
for (var prop in source) {
target[prop] = source[prop];
}
});
return target;
}
This script is larglely inspired from this question: Combine or merge JSON on node.js without jQuery
To have a cleaner code, I put this script in a library folder, and require it in my main script. This is what I did...
My lib/JSON.js file:
extends.merge = function(target){
// The same script as above.
}
and in my app.js file:
JSON = require('./lib/JSON')
It works well, but now, native JSON methods don't work (like .stringify). Then I digged a little bit, and tried to extend JSON using .prototype, like this (in lib/JSON.js):
extends.prototype.merge = ...
But get the following error:
TypeError: Cannot set property 'merge' of undefined
I really don't know what to do (and what I'm doing) since solving a problems causes another problem.
Please, need help.
Thanks.