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);
Related
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
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);
}
I have JSON that looks like this:
{
"status": {
"code": 0,
"message": "OK"
},
"data": {
"_idtype": "cusip",
"_id": "00768Y883",
"api": {
"_name": "PortfolioBreakdownsRaw",
"PortfolioDate": "2015-10-12",
"GlobalBondSuperSectorLongSalePositionBreakdown": [
{
"Name": "Municipal",
"Value": "0.57842"
},
{
"Name": "Corporate",
"Value": "1.79649"
},
{
"Name": "Securitized",
"Value": "5.29493"
},
{
"Name": "Cash & Equivalents",
"Value": "166.20776"
}
],
"GlobalBondSuperSectorShortSalePositionBreakdown": [
{
"Name": "Government",
"Value": "0.90557"
}
]
}
}
}
I am able to get the api portion of the response easily:
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
From here, I don't what if any arrays will be included in the response. The ultimate goal will be to create a parser that will be able to get the array names (GlobalBondSuperSectorShortSalePositionBreakdown) and as many rows of key-value pairs that it may contain, without first knowing the names such as (GlobalBondSuperSectorShortSalePositionBreakdown) beforehand.
I can't seem to find a good way to loop through the object, determine there are arrays at the api level and then iterate through those to get the values.
Any help would be appreciated.
Here's an example. In this code, the api variable holds a JObject, so we can iterate over its properties. From there, we look at the Type of each property value to see if it is an array or not. If it is, then we can iterate over that array to get the JObjects within it, and extract the Name and Value values that we expect to find there. Does this help?
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
foreach (JProperty prop in api.Children<JProperty>())
{
JToken value = prop.Value;
if (value.Type == JTokenType.Array)
{
Console.WriteLine(prop.Name + ": ");
foreach (JObject jo in value.Children<JObject>())
{
Console.WriteLine(" " + jo["Name"] + ": " + jo["Value"]);
}
}
else
{
Console.WriteLine(prop.Name + ": " + value);
}
}
Output:
_name: PortfolioBreakdownsRaw
PortfolioDate: 2015-10-12
GlobalBondSuperSectorLongSalePositionBreakdown:
Municipal: 0.57842
Corporate: 1.79649
Securitized: 5.29493
Cash & Equivalents: 166.20776
GlobalBondSuperSectorShortSalePositionBreakdown:
Government: 0.90557
Fiddle: https://dotnetfiddle.net/XyoXQy
With Linq you can play pretty nice with Json.net:
Here is an easily readable version of the chunk of code that will create two dictionaries out of the JArray properties under the api element:
var api = jObject["data"]["api"];
var arrays = api.Cast<JProperty>().Where(o => o.Value.Type == JTokenType.Array).Select(token => token.Value).ToArray();
var dictionaries = new List<Dictionary<string, string>>();
foreach (var array in arrays)
{
var dictionary = array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>());
dictionaries.Add(dictionary);
}
alternative:
The same thing, but a shorter, more compact version :
var api = jObject["data"]["api"];
var dictionaries = api
.Cast<JProperty>()
.Where(o => o.Value.Type == JTokenType.Array)
.Select(token => token.Value)
.Select(array => array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>()));
{
"isSuccessful": true,
"resultSet": [
{
"name": "pradeep",
"password": 123,
"timestamp": "2014-04-08T12:58:45.000Z"
},
{
"name": "dileep",
"password": 1234,
"timestamp": "2014-04-08T13:00:52.000Z"
}
]
}
This invocation result i have got by using Sql adapter so how to parse this invocation result and how can i display name,password,timestamp from this JSON object.Do i need to use HTTP Adapter.
If you want to get the length of results you should use result.invocationResult.resultSet.length which will give you the total number of results, where items is the response coming from the adapter and invocationResult contains the results and other paramaters, from which you will have to access the results for accessing only the particular output.To get value call
result.invocationResult.resultSet.name[position]
Like that call all the fields password,timestamp with position
in for loop
function handleSuccess(result) {
var invocationResult = result.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
var result = invocationResult.resultSet;
for ( var i = 0; i < result.length; i++) {
alert(result.name[i]);
alert(result.password[i]);
alert(result.timestamp[i]);
}
} else {
alert("error");
}
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);