Good way to convert JSON to Array - actionscript-3

i am trying to convert a json response to array in action script 3.
This is my JSON response:
[{
"id": 1,
"klistid": 8017,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 300,
"req": "gfi"
},
{
"id": 2,
"klistid": 8018,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 600,
"req": "gfi"
},
{
"id": 3,
"klistid": 8019,
"name": "List item name",
"description": "List item description",
"type": 1,
"offset": 900,
"req": "gfi"
}]
and this is my ac3 code:
function GetLists()
{
var req:URLRequest = new URLRequest("http://localhost:51318/api/List/1");
var ret:URLLoader = new URLLoader();
ret.addEventListener(Event.COMPLETE,function(e:Event)
{
var jsonData:Object = JSON.decode(ret.data);
for (var i:String in jsonData)
{
trace(i + ": " + jsonData[i]);
}
});
ret.load(req);
}
I assigned this function to a button but whenever i click that button nothing happens. I put traces in ac3 code when it enters the for loop code just stops and does nothing. I just want to convert this json string to an array or list to iterate through in it. I've already seen some posts about converting JSON strings to arrays but i have tried them all still nothing worked yet.
Thanks

There's a difference between your json data and the way to try to iterate on it.
Your data is an array with one element but you try to iterate on that one element like it should contain your objects id:1, 2, 3, etc ... Well of course it doesn't.
Instead remove the wrapper array from your json data or if you don't want to then:
var data:Object = jsonData[0];
for (var i:String in data)
{
trace(i)
}

All you have to do is cast your decoded data as an Array:
function GetLists()
{
var req:URLRequest = new URLRequest("http://localhost:51318/api/List/1");
var ret:URLLoader = new URLLoader();
ret.addEventListener(Event.COMPLETE,function(e:Event)
{
var jsonData:Array = JSON.decode(ret.data) as Array;
for each(var obj:Object in jsonData)
{
trace(obj["id"] + ": " + obj["description"]);
}
}
ret.load(req);
}

Related

get json object attribute with 'dot' in name

*** Problem solved : json.stringify was the problem.. much easier to handle when its gone.
var DBName = result['Document']['SW.Blocks.GlobalDB']['AttributeList']['Name'];
I have a xml file which describes a datablock from a PLC and want to get specific values with JS.
I converted it with xml2js module, so i have a json object to work with.
{
"Document": {
"Engineering": {
"$": {
"version": "V15"
}
},
"SW.Blocks.GlobalDB": {
"$": {
"ID": "0"
},
"HeaderAuthor": "",
"HeaderFamily": "",
"HeaderName": "",
"HeaderVersion": "0.1",
"Interface": {
...
...
"Name": "datentypen",
"Number": "6",
"ParameterModified": {
"_": "2018-09-05T11:49:37.0862092Z",
"$": {
"ReadOnly": "true"
}
},
}
}
I want to print out the "Name" and the "Number", which are part of the "AttributeList".
So how to handle with the "SW.Blocks.GlobalDB"?
Getting error : "TypeError: Cannot read property 'SW' of undefined"
var fs = require('fs');
var xml2js = require('xml2js');
var xml = fs.readFileSync('datentypen.xml');
var parser = new xml2js.Parser({explicitArray: false});
parser.parseString(xml, function(err, result) {
if (err) {
console.error('xml2js.parse error: ',err);
} else {
var injson = JSON.stringify(result,null,3);
console.log(injson);
// var injson2 = JSON.parse(injson);
// var DBnummer = injson.Document.SW.Blocks.GlobalDB.AttributeList["Name","Number"];
// console.log(DBNummer);
};
});
I read a lot about this theme but didnt found a concrete answer..
When i write ["SW.Blocks.GlobalDB"], an error about [ comes around.
Can you try reading the JSON array using Key-Value pair? I had similar issues but with a different programming language.

referencing objects in JSON

I have a code as a shown below in which I am not sure how to do referencing.
<p id="demo" ></p>
<p id="options"></p>
<script>
var myObj, myJSON, text, obj;
myObj = {
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
}
}
}
}
//Storing data:
// converting JS object into String
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
//Retrieving data:
text = localStorage.getItem("testJSON");
//converting String into JS object
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = // code
Problem Statement:
I am wondering what changes should I make in the below line(which is the last line in the above code) so that the output should be Huston Rocket.
document.getElementById("demo").innerHTML = // code
I tried in the following way but somehow I am not able to reach Huston Rocket
document.getElementById("demo").innerHTML = myObj.quiz.sport.q1.answer;
You are using incorrect name, after Json parsing, your Json object is 'obj'
So use it as
document.getElementById("demo").innerHTML = obj.quiz.sport.q1.answer;

Extract values from a parsed json object using a function node or split & switch node in NODE.red

Was trying to extract values from a parsed json object using a function node or split & switch node, tried to many ways and nothing seems to work fro me.
the example below I would like to have 5 outputs for the text and numeric values.
here is my payload in json:
{
"applicationID": "1",
"applicationName": "test_ds18b20",
"deviceName": "arduino_uno",
"devEUI": "1234567890123456",
"rxInfo": [
{
"mac": "aa755a0048050130",
"rssi": -57,
"loRaSNR": 10,
"name": "raspberry_pi",
"latitude": 1.466860686785175,
"longitude": 2.019478797912605,
"altitude": 0
}
],
"txInfo": {
"frequency": 868100000,
"dataRate": {
"modulation": "LORA",
"bandwidth": 125,
"spreadFactor": 7
},
"adr": true,
"codeRate": "4/5"
},
"fCnt": 9,
"fPort": 1,
"data": "Z29vZGJ5ZQ==",
"object": {}
}
first i try with function node to extract "data", but it returns array like this:
0: ""data":"Z29vZGJ5ZQ==""
1: "Z29vZGJ5ZQ=="
i dont need array i need string
function:
var regexsearch = /\"data\":\"(.*?)\"/i;
var my = msg.payload.match(regexsearch);
msg.payload = my;
return msg;
but i need to get only this Z29vZGJ5ZQ==
than i try with split & switch nodes and gets the whole linelike this: ""data":"Z29vZGJ5ZQ==""
but i need to get only this Z29vZGJ5ZQ==
and here is my flow:
[{"id":"d46d38e2.27cc78","type":"inject","z":"ff592a31.cf21a8","name":"","topic":"","payload":"{\"applicationID\":\"1\",\"applicationName\":\"test_ds18b20\",\"deviceName\":\"arduino_uno\",\"devEUI\":\"1234567890123456\",\"rxInfo\":[{\"mac\":\"aa755a0048050130\",\"rssi\":-57,\"loRaSNR\":10,\"name\":\"raspberry_pi\",\"latitude\":48.466860686785175,\"longitude\":35.019478797912605,\"altitude\":0}],\"txInfo\":{\"frequency\":868100000,\"dataRate\":{\"modulation\":\"LORA\",\"bandwidth\":125,\"spreadFactor\":7},\"adr\":true,\"codeRate\":\"4/5\"},\"fCnt\":9,\"fPort\":1,\"data\":\"Z29vZGJ5ZQ==\",\"object\":{}}","payloadType":"json","repeat":"","crontab":"","once":false,"x":90,"y":160,"wires":[["1a34819e.743eee"]]},{"id":"105db6d9.0df1c9","type":"debug","z":"ff592a31.cf21a8","name":"","active":true,"console":"false","complete":"false","x":610,"y":100,"wires":[]},{"id":"1ac8a3e1.8f379c","type":"split","z":"ff592a31.cf21a8","name":"","splt":",","spltType":"str","arraySplt":"1","arraySpltType":"len","stream":false,"addname":"","x":250,"y":340,"wires":[["c10ec515.102d38"]]},{"id":"c10ec515.102d38","type":"switch","z":"ff592a31.cf21a8","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"\"data\":","vt":"str"},{"t":"cont","v":"\"latitude\":","vt":"str"}],"checkall":"true","outputs":2,"x":370,"y":340,"wires":[["105db6d9.0df1c9"],["6b2d5d19.7868e4"]]},{"id":"1a34819e.743eee","type":"json","z":"ff592a31.cf21a8","name":"","pretty":false,"x":115.55555555555556,"y":312.22222222222223,"wires":[["1ac8a3e1.8f379c","bae9fa5d.a9f238"]]},{"id":"bae9fa5d.a9f238","type":"function","z":"ff592a31.cf21a8","name":"match","func":"var regexsearch = /\\\"data\\\":\\\"(.*?)\\\"/i;\nvar my = msg.payload.match(regexsearch);\nmsg.payload = my;\nreturn msg;","outputs":1,"noerr":0,"x":310,"y":160,"wires":[["105db6d9.0df1c9"]]},{"id":"6b2d5d19.7868e4","type":"debug","z":"ff592a31.cf21a8","name":"","active":true,"console":"false","complete":"false","x":610,"y":180,"wires":[]}]
Thanks for help

How can i get an array of images from a collection of nested objects with Lodash?

{
"shop": {
"homebackground": "http://padmenu.s3.amazonaws.com/15/11/2014/05/08/2ec2ff61-d6a0-11e3-8857-10ddb1e6e201.jpg",
"name": {
"tr": "My Shop"
},
"menus": [{
"name": {
"en": "Menu"
},
"children": [{
"name": {
"en_US": "Category"
},
"images": [
"http://www.progressivedental-ellenlimdds.com/wp-content/uploads/2014/06/red-wine.jpg"
],
"children": [{
"name": {
"en_US": "Item"
},
"images": [
"http://res.cloudinary.com/finedine/image/upload/c_fill,g_center,h_600/v1435916818/WIne-Bottle_uz03a0.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3",
"http://lorempixel.com/400/400/food/4",
"http://lorempixel.com/400/400/food/5",
"http://lorempixel.com/400/400/food/6",
"http://lorempixel.com/400/400/food/7"
]
}]
}]
}]
}
}
I want to select all the "images" arrays from shop's "children" objects.
How can i do this by using Lodash library?
The output should be an array of consists of image urls:
["url1","url2","url3"]
The easiest approach to solve this problem is by plucking through children and their descendants recursively. The important points are in the getImages() function; wherein it flattens all children arrays in one level, pluck each image arrays and compact all items to remove undefined values(caused by children with no images), and then flattening the images array and readied for concatenation. The stopping point of the recursion is when there are no images for the current children, returning an empty array. If images are found, then we recursively concatenate all potential descendant images. As to how we get the descendants, we use the same chaining sequence that we used in getting the images array but with children as the plucking key.
DEMO
function getImages(children) {
var images = _(children).flatten().pluck('images').compact().flatten().value();
if(_.isEmpty(images)) {
return [];
}
var descendants = _(children).flatten().pluck('children').compact().flatten().value();
return images.concat(getImages(descendants));
}
function getShopImages(data) {
var children = _.pluck(data.shop.menus, 'children');
return getImages(children);
}
console.log(getShopImages(data));
Pseudo Code
You can solve this with a little bit of recursion:
Grab the children list.
Extract all the images from the children list with pluck.
Repeat step 1 with all descendants.
Concat all results and flatten.
Core Code
function deepExtract(collection, childKey, property) {
var exists = _.negate(_.isEmpty);
var children = _.chain(collection).pluck(childKey).filter(exists).flatten();
if (_.isEmpty(children.value())) {
return [];
}
var images = children.pluck(property).value();
var descendantImages = deepExtract(children.value(), childKey, property);
return _.flatten(images.concat(descendantImages));
};
var tree = _.chain(data).get('shop.menus').value();
var images = deepExtract(tree, 'children', 'images');
Demo
var data = {
"shop": {
"homebackground": "http://padmenu.s3.amazonaws.com/15/11/2014/05/08/2ec2ff61-d6a0-11e3-8857-10ddb1e6e201.jpg",
"name": {
"tr": "My Shop"
},
"menus": [{
"name": {
"en": "Menu"
},
"children": [{
"name": {
"en_US": "Category"
},
"images": [
"http://www.progressivedental-ellenlimdds.com/wp-content/uploads/2014/06/red-wine.jpg"
],
"children": [{
"name": {
"en_US": "Item"
},
"images": [
"http://res.cloudinary.com/finedine/image/upload/c_fill,g_center,h_600/v1435916818/WIne-Bottle_uz03a0.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3",
"http://lorempixel.com/400/400/food/4",
"http://lorempixel.com/400/400/food/5",
"http://lorempixel.com/400/400/food/6",
"http://lorempixel.com/400/400/food/7"
]
}]
}]
}]
}
};
function deepExtract(collection, childKey, property) {
var exists = _.negate(_.isEmpty);
var children = _.chain(collection).pluck(childKey).filter(exists).flatten();
if (_.isEmpty(children.value())) {
return [];
}
var images = children.pluck(property).value();
var descendantImages = deepExtract(children.value(), childKey, property);
return _.flatten(images.concat(descendantImages));
};
var tree = _.chain(data).get('shop.menus').value();
log(deepExtract(tree, 'children', 'images'));
// Helper method to output to screen
function log(value) {
document.getElementById("output").innerHTML += JSON.stringify(value, null, 2) + "\n"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<pre id="output"></pre>
I found an alternative solution to my question here:
var children = _(shop.menus[0].children)
.thru(function(coll) {
return _.union(coll, _.pluck(coll, 'children'));
})
.flatten();
var images = _.chain(children).pluck('images').flattenDeep().compact().uniq().value();
The output "images" is an image array.

JSONPath expression to search for objects with certain property in different tree branches

I am looking for a JSONPath expression that returns all zone objects with zoneType "big".
Input JSON:
{
"board" : {
"zones" : {
"1": {
"zoneID": 1,
"zoneType":"big"
},
"2": {
"zoneID": 2,
"zoneType":"small"
},
"3": {
"zoneID": 3,
"zoneType":"small"
},
"4": {
"zoneID": 4,
"zoneType":"big"
},
}
}
}
Expected Output:
[{
"zoneID": 1,
"zoneType":"big"
},
{
"zoneID": 4,
"zoneType":"big"
}]
I have tried:
$..zones.[?(#.zoneType='big')]
$..zones.*[?(#.zoneType='big')]
and many others but no luck.
i too initially used jsonpath then later got stuck with some problem so decided to use
looping through the data.so can you try with the below piece of code.
var json = ur json data;
var output = (function (data) {
var keys = (function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
})(data["board"]["zones"]);
var categoryFilter = new Function('data,keys',
"obj=[];" +
"for(var i=0;i<keys.length;i++){" +
"if (data[keys[i]].zoneType == 'big') {" +
"obj.push(data[keys[i]]);" +
"}" +
"}" +
"return obj;"
);
return JSON.stringify(categoryFilter(data["board"]["zones"], keys));
})(json);
Answer should be: $..zones[?(#.zoneType=="big")]
Following works :-
JsonPath.on(json_hash, '$..zones[?(#.zoneType=="big")]')
returns:-
[{"zoneID"=>1, "zoneType"=>"big"}, {"zoneID"=>4, "zoneType"=>"big"}]
JSONPath is unstandardised "query language" but XPath is. Using DefiantJS, you can query JSON structure with XPath expressions. This library extends the global object JSON with the method "search" and it returns matches as an array like object.
Below is example code (and here is the fiddle http://jsfiddle.net/hbi99/DQ9CJ/):
var data = {
"board": {
"zones": {
"1": {
"zoneID": 1,
"zoneType": "big"
},
"2": {
"zoneID": 2,
"zoneType": "small"
},
"3": {
"zoneID": 3,
"zoneType": "small"
},
"4": {
"zoneID": 4,
"zoneType": "big"
}
}
}
},
found = JSON.search(data, '//*[zoneType="big"]'),
str = '';
for (var i=0; i<found.length; i++) {
str += found[i].zoneID +'<br/>';
}
document.getElementById('output').innerHTML = str;