Titanium - Unable to Parse local JSON file - json

I am trying to parse a local JSON file that has been stored in the applicationDataDirectory. Im just needing to grab items from this file. Running V.2 of titanium
The JSON data structure looks like this
{
"object_name": [
{
"title": "Burrton",
"value": "Burrton",
"homeof": "Chargers",
"logo": "images/logos/BURRTON.jpg",
"colors": "#cccccc;#a9a9a9",
"links": {
"tsr": "http://www.schurzdigital.com/mfeeds/CollectionFeed.php?site=http%3A%2F%2Fwww.catchitkansas.com&collection=cik_burrton_headlines&title=cik_burrton_headlines&limit=25",
"sports": "www.schurzdigital.com/mfeeds/CollectionFeed.php?site=http%3A%2F%2Fwww.catchitkansas.com&collection=cik_burden_headlines&title=cik_burden_headlines&limit=25",
"videos": "http://www.schurzdigital.com/mfeeds/TividFeedConvert.php?site=http%3A%2F%2Fwww.catchitkansas.com&slug=e9c0b075-3230-4a45-803e-7ccb4b7f754e&title=Top%20videos&limit=25",
"photos": "http://serve.a-feed.com/service/getFeed.kickAction?feedId=1014509&as=8768",
"stats": {
"boys": {
"football": "http://stats.catchitkansas.com/report_fb-schedule_results.php?sport=15&team=763",
"basketball": "http://stats.catchitkansas.com/report_baskb-schedule_results.php?sport=26&team=2946",
"cross country": "http://stats.catchitkansas.com/report_cc-schedule_results.php?sport=13&team=764",
"golf": "http://stats.catchitkansas.com/report_golf-schedule_results.php?sport=16&team=767",
"track": "http://stats.catchitkansas.com/report_trackfield-schedule_results.php?sport=32&team=2948"
},
"girls": {
"volleyball": "http://stats.catchitkansas.com/report_vb-schedule_results.php?sport=22&team=766",
"basketball": "http://stats.catchitkansas.com/report_baskb-schedule_results.php?sport=27&team=2947",
"cross country": "http://stats.catchitkansas.com/report_cc-schedule_results.php?sport=13&team=764",
"golf": "http://stats.catchitkansas.com/report_golf-schedule_results.php?sport=17&team=768",
"track": "http://stats.catchitkansas.com/report_trackfield-schedule_results.php?sport=32&team=2948"
}
}
}
}
]
}
The Code im using to parse the file.
var fileName = 'school_select.json';
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fileName);
if (file.exists()) {
var json = file.read();
var jsonObject = JSON.parse(json);
one.text = jsonObject.object_name[0].title;
two.text = jsonObject.object_name[0].homeof;
}

I answered my own question. I used the following code.
var fileName = 'school_select.json';
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, fileName);
var json, object_name, locatie, i, row, title, value, homeof, logo, colors, link;
var preParseData = (file.read().text);
var response = JSON.parse(preParseData);
Ti.API.info('title = ' + response.object_name[0].title);

Related

BinaryFormatter has been deprecated, how to deserialize entire object graph from json

update:
In newtonsoft, it works fine like this.
var saveObject = Newtonsoft.Json.JsonConvert.SerializeObject(root, Newtonsoft.Json.Formatting.Indented);
var root2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Node>(saveObject);
Here, the entire "tree"/graph is reloaded into root2. Is this behaviour accomplishable with System.Text.Json?
original question:
I have a data model (more precisely a DOM) where I have been using BinaryFormatter to serialize and deserialize the entire graph of connected various objects. It has worked flawless for years. Now, the binaryFormatter has been deprecated, and Microsoft appears to suggest that one should use Json for the job.
Using System.Text.Json serializing the dom, the entire graph is serialized easily, however, when deserializing, only the root level node is deserialized. Any objects hanging on the root node is not deserialized. What am I missing to reload the entire graph? Annotations on the list property? Could anyone guide me to a good example? Or, any other good suggestions to save a dom on disc? Thank you.
using System.Text.Json;
var root = new Node("root");
var a1 = new Node("a1");
var a2 = new Node("a2");
var b11 = new Node("b11");
var b12 = new Node("b12");
var b21 = new Node("b21");
var b22 = new Node("b22");
root.Nodes.Add(a1);
root.Nodes.Add(a2);
a1.Nodes.Add(b11);
a1.Nodes.Add(b12);
a2.Nodes.Add(b21);
a2.Nodes.Add(b22);
var options = new JsonSerializerOptions { WriteIndented = true, };
string saveFile = JsonSerializer.Serialize(root,options);
Console.WriteLine("Savefile:");
Console.WriteLine(saveFile);
var loadFile = JsonSerializer.Deserialize<Node>(saveFile,options)!;
Console.WriteLine();
Console.WriteLine("Loadfile:");
Console.WriteLine(loadFile);
public class Node
{
public Node(string name)
{
Name = name;
}
public string Name { get; set; }
public List<Node> Nodes { get; set; } = new List<Node>();
}
Output:
Savefile:
{
"Name": "root",
"Nodes": [
{
"Name": "a1",
"Nodes": [
{
"Name": "b11",
"Nodes": []
},
{
"Name": "b12",
"Nodes": []
}
]
},
{
"Name": "a2",
"Nodes": [
{
"Name": "b21",
"Nodes": []
},
{
"Name": "b22",
"Nodes": []
}
]
}
]
}
Loadfile:
Node

Need help in Append JSON file using ContentMerge in Apache NIFi

I'm trying to merge a JSON file which has multiple objects. Below is my Oringinal JSON file.
{
"applicant": {
"full-name": "Tyrion Lannister",
"mobile-number" : "8435739739",
"email-id" : "tyrionlannister_casterlyrock#gmail.com"
},
"product": {
"product-category" : "Credit Card",
"product-type" : "Super Value Card - Titanium"
}
}
I will get some more JSON data as below from other source.
{
"flags": {
"duplicate-flag" : "No"
"contact-flag" : "Yes"
}
}
My task is to append the new JSON in the old JSON recods as a new object as below.
{
"applicant": {
"full-name": "Tyrion Lannister",
"mobile-number" : "8435739739",
"email-id" : "tyrionlannister_casterlyrock#gmail.com"
},
"product": {
"product-category" : "Credit Card",
"product-type" : "Super Value Card - Titanium"
},
"flags": {
"duplicate-flag" : "No"
"contact-flag" : "Yes"
}
}
Can someone help to guide, how it can be achieved in NiFi ?
I recommend accumulating your components as flowfile attributes, then forming a merged object with an ExecuteScript processor using JavaScript/ECMAScript. Sometimes there's just no substitute for JavaScript. Something like the following might work:
flowFile = session.get();
if (flowFile != null) {
var OutputStreamCallback = Java.type("org.apache.nifi.processor.io.OutputStreamCallback");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
// Get attributes
var applicant = JSON.parse(flowFile.getAttribute("applicant"));
var product = JSON.parse(flowFile.getAttribute("product"));
var flags = JSON.parse(flowFile.getAttribute("flags"));
// Combine
var merged = {
"applicant": applicant,
"product": product,
"flags": flags
};
// Write output content
flowFile = session.write(flowFile, new OutputStreamCallback(function(outputStream) {
outputStream.write(JSON.stringify(merged, null, "\t").getBytes(StandardCharsets.UTF_8));
}));
session.transfer(flowFile, REL_SUCCESS);
}

best way to parse nested object in AngularJS?

I'm trying to use angularjs for parsing a nested data structure returned from a remote server. I'm really stumped by this pattern because i'm trying to access the "events" data with the following function
$scope.generate_event = function(){
from_date = $scope.dts.from
to_date = $scope.dts.to
from = from_date.getFullYear()+'/'+(from_date.getMonth()+1)+'/'+from_date.getDate()
to = to_date.getFullYear()+'/'+(to_date.getMonth()+1)+'/'+to_date.getDate()
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&evfields=lat,lon,f_event_time,speed&from='+from+'&to='+to)
.success(function(data){
$scope.report_data = data
$localStorage.report_data = data
$scope.generate()
})
}
Any advice or even a hint on the best approach would be great, i need this running for work and its been a month now. Thanks!
{
"rawData": {
"keys": {
"lat": ["number", "lat"],
"lon": ["number", "lon"],
"speed": ["number", "Speed [mph]"],
"code": ["number", "EVC"],
"vid": ["number", "Vehicle ID"]
},
"keys_order": ["lat", "lon", "speed", "code", "vid"],
"events": [{
"f_lon": -8.3315599999999996,
"code": 4,
"vid": 5,
"lon": -833156,
"f_lat": 51.90831,
"lat": 5190831,
"speed": 78.0
}, {
"f_lon": -8.3741599999999998,
"code": 4,
"vid": 5,
"lon": -837416,
"f_lat": 51.903979999999997,
"lat": 5190398,
"speed": 78.0
}]
}
}
UPDATE: I didnt explain the problem correctly. Here's the generate function
$scope.generate = function(){
$scope.event_config = {
title: 'Events', // chart title, legend etc
/*etc
*etc
*/
data = {}
data.series = [' Events']
data.data = []
this fucker ----->$scope.report_data.events.forEach(function(value, index, array){
o = {}
o.x = value.f_event_time
o.y = [value.lat+'/'+value.lon]
o.tooltip = value.speed
data.data.push(o)
})
$scope.event_data = data
I'm getting error 'forEach undefined'. This is supposed to generate a d3 chart but 'report_data' is intially used to store distance data from a different function for local storage. So do i need a second variable for localStorage? ie $scope.report_event = $localStorage.report_event? Can someone look at the source code if i send it?
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&evfields=lat,lon,f_event_time,speed&from='+from+'&to='+to)
.success(function(data){
if (data) {
var events = data.rawData.events; // get the events json array
$scope.generate(events);
}
})
and in your controller have the declarative function like
$scope.generate = function(events) {
// your code
}
Solved it with the following
$scope.generate_report = function(){
from_date = $scope.dts.from
to_date = $scope.dts.to
from = from_date.getFullYear()+'/'+(from_date.getMonth()+1)+'/'+from_date.getDate()
to = to_date.getFullYear()+'/'+(to_date.getMonth()+1)+'/'+to_date.getDate()
$http.get(server+'vehicle/'+$scope.selected_vehicle.id+'/counters/deltas/day?from='+from+'&to='+to)
.success(function(data){
$scope.report_data = data
$localStorage.report_data = data
$scope.process()
})
$http.get(server+'rawdata?vids='+$scope.selected_vehicle.id+'&genevcodes=39,40&evfields=lat,lon,f_event_time,mph,speed,code&from='+from+'&to='+to)
.success(function(data){
if(data){
var events = data.rawData.events
}
$scope.report_event = events
$localStorage.report_event = events
$scope.generate()
})
}
just had to declare another localstorage variable for storing events from the JSON object Thanks Yannik

Json object merge with unqiue id

I have multiple json Objects
json1 = [
{'category_id':1,'name':'test1' },
{'category_id':1,'name':'test2' },
{'category_id':1,'name':'test3' },
{'category_id':2,'name':'test2' },
{'category_id':3,'name':'test1' }
];
json2 = [{'category_id':1,'type':'test1'}];
json3 = [
{'category_id':1,'color':'black'},
{'category_id':2,'color':'black'},
{'category_id':3,'color':'white'}
];
I am expecting output like this
final = [
{'category_id':1,'name':'test1','type':'test`','color':'black' },
{'category_id':1,'name':'test2','type':'test`','color':'black' },
{'category_id':1,'name':'test3','type':'test`','color':'black' },
{'category_id':2,'name':'test2','color':'black' },
{'category_id':3,'name':'test1','color':'white' }
];
As i have long json object. Looping is good idea or not ? Does there is any inbuilt function for doing the same.
Using underscore you can achieve it via:
Demo Fiddle
var jsons = [json1, json2, json3];
var final = {};
// merge all data
_.each(jsons, function (jsonArr) {
_.each(jsonArr, function (json) {
final[json.category_id] = _.extend({}, final[json.category_id], json);
});
});
// map it back onto json1
var finalArr = _.map(json1, function (json) {
return final[json.category_id];
});
console.log(finalArr);
Final value of finalArr:
Here is how you can do the same in plain javascript. :)
var final = {};
var jsons = [json1, json2, json3];
for(var i=0;i<jsons.length;i++){
final[i]=jsons[i];
}
Fiddle
EDIT:
Well, you will have to do it programmatically!

Actionscript3 parsing json with an object

I have a flash app where in a function I have to parse a json passed like an object by some external API that I can't change.
my json look like this:
{
"prodotti": [
{
"titolo": "test",
"marca": "",
"modello": "",
"cilindrata": "",
"potenza": "",
"alimentazione": "",
"images": {
"img": [
{
"thumb": "admin/uploads/img_usato/small/qekabw95L5WH1ALf6.jpg",
"big": "admin/uploads/img_usato/big/qekabw95L5WH1ALf6.jpg"
},
{
"thumb": "admin/uploads/img_usato/small/default.jpg",
"big": "admin/uploads/img_usato/big/default.jpg"
}
]
}
},
{
"titolo": "Motore Volvo TAMD 74 C",
"marca": "VOLVO PENTA",
"modello": "TAMD 74 C",
"cilindrata": "7.283 cm3",
"potenza": "331 kW a 2600 rpm",
"alimentazione": "Gasolio",
"images": {
"img": [
{
"thumb": "admin/uploads/img_usato/small/PmQwN4t4yp7P1YCWa.jpg",
"big": "admin/uploads/img_usato/big/PmQwN4t4yp7P1YCWa.jpg"
},
{
"thumb": "admin/uploads/img_usato/small/BWkjTGcy3pDM2LKRs.jpg",
"big": "admin/uploads/img_usato/big/BWkjTGcy3pDM2LKRs.jpg"
}
]
}
}
]
}
I want to parse the images inside the object.
The API send me an object not astring or json and I have this function now:
function changeData (prodotto:Object) {
img_container.graphics.clear ();
//here I want to enter and take thumb and big of images!!!
for (var index in prodotto.images.img) {
//trace('index: ' + index);
//trace("thumb: " + index.thumb + ' big: ' + index.big);
}
descrizione.htmlText = prodotto.testo_html;
titolo.text = prodotto.titolo;
alimentazione.text = prodotto.alimentazione;
potenza.text = prodotto.potenza;
cilindrata.text = prodotto.cilindrata;
modello.text = prodotto.modello;
marca.text = prodotto.marca;
}
The function works fine but not for the for loop where I try to take the bug and thumb of my json how can I retrieve this information in this object?
Thanks
I think there is something wrong with how you are setting up the call back but since you didn't show code for the api we can't fix that, plus you stated you have no control over it.
No matter what the issue is it just does not seem correct.
I put together a function that will get all the thumbs and bigs.
You did not state otherwise.
function changeData (prodotto:Object) {
for each(var item in prodotto.prodotti){
trace('')
//trace(prodotto.testo_html);
trace(item.titolo);
trace(item.alimentazione);
trace(item.potenza);
trace(item.cilindrata);
trace(item.modello);
trace(item.marca);
for each( var imgs in item.images.img) {
trace('thumb',imgs.thumb)
trace('big',imgs.big)
}
}
}
I think you need to use a JSON parser. Use the one from this link: https://github.com/mikechambers/as3corelib
1: Add the com folder to your project directory or add it to your default class path.
2: Adapt this code to your liking. I am not sure how you're getting a literal object from the API. It really should just be a string unless you're using some sort of AMF. Regardless...
import com.adobe.serialization.json.*;
var data:String = '{"prodotti":[{"titolo":"test","marca":"","modello":"","cilindrata":"","potenza":"","alimentazione":"","images":{"img":[{"thumb":"admin/uploads/img_usato/small/qekabw95L5WH1ALf6.jpg","big":"admin/uploads/img_usato/big/qekabw95L5WH1ALf6.jpg"},{"thumb":"admin/uploads/img_usato/small/default.jpg","big":"admin/uploads/img_usato/big/default.jpg"}]}},{"titolo":"Motore Volvo TAMD 74 C","marca":"VOLVO PENTA","modello":"TAMD 74 C","cilindrata":"7.283 cm3","potenza":"331 kW a 2600 rpm","alimentazione":"Gasolio","images":{"img":[{"thumb":"admin/uploads/img_usato/small/PmQwN4t4yp7P1YCWa.jpg","big":"admin/uploads/img_usato/big/PmQwN4t4yp7P1YCWa.jpg"},{"thumb":"admin/uploads/img_usato/small/BWkjTGcy3pDM2LKRs.jpg","big":"admin/uploads/img_usato/big/BWkjTGcy3pDM2LKRs.jpg"}]}}]}';
function changeData(data)
{
img_container.graphics.clear();
var obj = JSON.decode(data);
for (var i:int = 0; i < obj.prodotti.length; i++)
{
for (var k in obj.prodotti[i].images.img)
{
trace("Thumb:",obj.prodotti[i].images.img[k].thumb);
trace("Big:",obj.prodotti[i].images.img[k].big);
}
descrizione.htmlText = obj.prodotti[i].testo_html;
titolo.text = obj.prodotti[i].titolo;
alimentazione.text = obj.prodotti[i].alimentazione;
potenza.text = obj.prodotti[i].potenza;
cilindrata.text = obj.prodotti[i].cilindrata;
modello.text = obj.prodotti[i].modello;
marca.text = obj.prodotti[i].marca;
}
}
changeData(data);