Get nested Childrens in JSON using Angular2 - json

I'm working on json Data with inner childrens. i need to get all the name's in the json.
json data
this.res = [
{
"children": [
{
"children": [
{
"children": [],
"name": "P Sub Child 3",
},
{
"children": [
{
"children":[],
"name" : "data"
}
],
"name": "PSubChild2",
}
],
"name": "PChild1",
},
{
"children": [
{
"children": [],
"name": "PSubChild3",
}
],
"name": "PChild2",
}
],
"name": "Parent1",
},
{
"children": [],
"name": "Parent2",
}
];
in my application names of every child has to store in the variables using angular2.
Data is dynamic changes as per the user in my application

From what I understand you want to just get the value of the name property down the hierarchical data you have then as most here suggested you have to use recursion to get to the name property. With Rxjs it becomes a bit easier to do like following:
Observable.from(this.res)
.expand(d => d.children.length > 0 ? Observable.from(d.children) : Observable.empty())
.subscribe(d => console.log(d.name));
I have made a working sample here: https://jsfiddle.net/ibrahimislam/ba17w8xz/1/

Here is a plunkr of a possible implementation
https://plnkr.co/edit/njM1HLx7vuZY9loto2pM?p=preview
Create your own datatype:
export class MyNode {
children:Array<MyNode>;
name:string;
}
and then create a method to recursively loop your parents to get their names and the names of the children
parents:Array<MyNode> = [
{
"children": [
{
"children": [
{
"children": [],
"name": "P Sub Child 3",
},
{
"children": [
{
"children":[],
"name" : "data"
}
],
"name": "PSubChild2",
}
],
"name": "PChild1",
},
{
"children": [
{
"children": [],
"name": "PSubChild3",
}
],
"name": "PChild2",
}
],
"name": "Parent1",
},
{
"children": [],
"name": "Parent2",
}
];
names:Array<string>=[];
getAllNames(){
this.getNameHelper(this.parents);
}
getNameHelper(parents:Array<MyNode>){
for(var p of parents){
if(p.name){
this.names.push(p.name);
}
if(p.children){
this.getNameHelper(p.children);
}
}
}

Related

jsonschema Required properties inoperative with $ref

I am going to write json schema to verify tree data.
Schema consisting of top root and block below.
There may be another block below the block.
Schema for validation.
schema = {
"$schema": "http://json-schema.org/draft-04/schema",
"$ref": "#/definitions/root",
"definitions":{
"root": {
"properties": {
"name": {
"type": "string"
},
"children": {
"type": "array",
"items": [
{"$ref":"#/definitions/block"}
]
}
},
"required": ["name", "children"]
},
"block": {
"properties": {
"name": {
"type": "string"
},
"children": {
"type": "array",
"items": [
{"$ref":"#/definitions/block"}
]
}
},
"required": ["name"]
}
}
}
Below is incorrect data for testing. The last name properties do not exist.
{
"name": "group8",
"children": [
{
"name": "group7",
"children": [
{
"name": "group6",
"children": [
{
"name": "group5",
"children": [
{ ###### wrong
"children": []
}
]
}
]
}
]
}
]
}
This data validates well, but it doesn't work on a slightly complex tree.
# Error: ValidationError: file /home/gulliver/.local/lib/python2.7/site-packages/jsonschema/validators.py line 934: 'name' is a required property #
{
"name": "group8",
"children": [
{
"name": "group7",
"children": [
{
"name": "group6",
"children": [
{
"name": "group12",
"children": [
{
"name": "group11",
"children": [
{
"name": "group10",
"children": []
}
]
}
]
},
{
"name": "group9",
"children": [
{
"name": "group5",
"children": [
{ ####### wrong
"children": []
}
]
}
]
}
]
}
]
},
{
"name": "group13",
"children": [
{
"name": "null1",
"children": []
}
]
}
]
}
It does not work when the data at the bottom of the tree is invalid.
My guess is that the branch splits and this happens, does anyone know why or how to fix it?
I tested using python and jsonschema.
When items is an array, it applies the subschema values to the same index location in the array in the instance.
For example, where you define...
"items": [
{"$ref":"#/definitions/block"}
]
only the first item in the array will be tested. It has nothing to do with deep nesting. For example, the follwing data is valid according to your schema...
{
"name": "group8",
"children": [
{
"name": "group7"
},
{
"something": "else",
"Not": "name"
}
]
}
(Live demo: https://jsonschema.dev/s/etFGE)
If you modify your use of items, then it will work like you expect:
"items": {"$ref":"#/definitions/block"}
(do this for both uses)
Live demo: https://jsonschema.dev/s/rk1OD

How can I create a hierarchical json response in FLASK

I have a single table in database like database table. I want to search a child from database and return a hierarchical JSON to a front end in order to create a tree. How can I do that in FLASK.
My expected JSON for mat should be like expected JSON
Since you have tagged your question with flask, this post assumes you are using Python as well. To format your database values in JSON string, you can query the db and then use recursion:
import sqlite3, collections
d = list(sqlite3.connect('file.db').cursor().execute("select * from values"))
def get_tree(vals):
_d = collections.defaultdict(list)
for a, *b in vals:
_d[a].append(b)
return [{'name':a, **({} if not (c:=list(filter(None, b))) else {'children':get_tree(b)})} for a, b in _d.items()]
import json
print(json.dumps(get_tree(d), indent=4))
Output:
[
{
"name": "AA",
"children": [
{
"name": "BB",
"children": [
{
"name": "EE",
"children": [
{
"name": "JJ",
"children": [
{
"name": "EEV"
},
{
"name": "FFW"
}
]
},
{
"name": "KK",
"children": [
{
"name": "HHX"
}
]
}
]
}
]
},
{
"name": "CC",
"children": [
{
"name": "FF",
"children": [
{
"name": "LL",
"children": [
{
"name": "QQY"
}
]
},
{
"name": "MM",
"children": [
{
"name": "RRV"
}
]
}
]
},
{
"name": "GG",
"children": [
{
"name": "NN",
"children": [
{
"name": "SSW"
}
]
}
]
}
]
},
{
"name": "DD",
"children": [
{
"name": "HH",
"children": [
{
"name": "OO",
"children": [
{
"name": "TTZ"
}
]
}
]
},
{
"name": "II",
"children": [
{
"name": "PP",
"children": [
{
"name": "UUW"
}
]
}
]
}
]
}
]
}
]

Getting all subitems from all documents with a Couchbase map/reduce view

I have Couchbase documents with structure like this:
{
"subscriberIds": [
{
"type": "END_USER",
"identity": "00000000223"
}
],
"userDataId": "SUB-00000000223",
"status": "ACTIVATED",
"subscriptions": [
{
"id": "Something1",
"attributes": [
{
"value": "Active",
"name": "Status"
}
],
"priority": "1",
"subscriptionStartDate": somedate,
"productShortName": "Something1"
},
{
"id": "Something2",
"attributes": [
{
"value": "Active",
"name": "Status"
}
],
"priority": "1",
"subscriptionStartDate": somedate,
"productShortName": "Something2"
}
],
}
And I'm trying to write a view to get all the 'subscriptions' from all documents in bucket as:
{"total_rows":900,"rows":[
{"id":"Something1","key":null,"value":"00000000223"},
{"id":"Something2","key":null,"value":"00000000223"},
...
but, I can't get nested item from doc
function (doc, meta) {
for (var i in doc.subscriptions) {
emit(doc.subscriptions.id, doc.id);
}
}
I know this is possible, but apparently I do not fully understand the concept of views.
for (var i in doc.subscriptions) {
emit(doc.subscriptions[i].id, doc.id);
}

Merge the JSON data with same value in typescript

I have a JSON Data that I am getting from URL. I want to merge the data which has same Value Below is the sample data. I have searched through the Internet,but i didn't got the solution. All i found is for same Keys.
[ {
"banana": [
{
"color": yellow,
"size": "small"
},
{
"size": "medium"
},
{
"size": "large"
}
],
"process_name": "fruits"},{
"carnivores": [
{
"name": "lion"
},
{
"name": "tiger"
},
{
"name": "chetah"
},
{
"name": "dianosaur"
}
],
"process_name": "animal"}, {
"apple": [
{
"color": red,
"size": "large"
}
],
"process_name": "fruits"}]
And I want to merge the data of "process_name" :"fruits" into one array as below and the result should be
[{
"banana": [
{
"color": yellow,
"size": "small"
},
{
"size": "medium"
},
{
"size": "large"
}
],
"apple": [
{
"color": red,
"size": "large"
}
],
"process_name": "fruits" }, {
"carnivores": [
{
"name": "lion"
},
{
"name": "tiger"
},
{
"name": "chetah"
},
{
"name": "dianosaur"
}
],
"process_name": "animal"}]
can anyone help on this?
Just some snippet to start:
// data definition
const json_before = [ {
"banana": [
{
"color": "yellow",
"size": "small"
},
{
"size": "medium"
},
{
"size": "large"
}
],
"process_name": "fruits"},
{
"carnivores": [
{
"name": "lion"
},
{
"name": "tiger"
},
{
"name": "chetah"
},
{
"name": "dianosaur"
}
],
"process_name": "animal"},
{
"apple": [
{
"color": "red",
"size": "large"
}
],
"process_name": "fruits"
}];
// processing
const json_after = json_before.reduce((arr, next) => {
const exist = arr.find(el => el.process_name === next.process_name);
if (exist) Object.assign(exist, next);
else arr.push(next);
return arr;
}, []);
// check
console.log(json_after);
The main idea is to use reduce for array traversing. To shorten the processing code, I've used Object.assign to modify previuosly added element, although in real code it's better to use Object.keys and manually check whether the properties of the previous object aren't overwritten.
Note that this is mutating the source data (check by adding console.log(json_before)). Again, if you don't want this, you should clone each element yourself, without direct object assignment.

Traversing through nested json in scala play

I'm using scala play and am attempting to traverse a json tree in order to validate that specific name values have specific children with specific name values. I have the following Json in the form of a JsObject:
{ "name": "user", "children": [ { "name": "$a", "children": [ { "name": "foo", "children": [ ] }, { "name": "fooBar", "children": [ { "name": "$a", "children": [ { "name": "subFoobar1", "children": [ ] }, { "name": "subFoobar2", "children": [ { "name": "TEST", "children": [ ] } ] }, { "name": "subFoobar3", "children": [ ] } ] } ] }, { "name": "bar", "children": [ { "name": "$a", "children": [ ] }, { "name": "$c", "children": [ ] }, { "name": "$b", "children": [ ] } ] }, { "name": "barFoo", "children": [ ] } ] } ] }
Ideally I would use nested for loops to traverse but the JsObject structure is preventing me from accessing the underlying values when attempting traverse. I have also attempted mapping the JsObject to a map of type [Map[String,Map[String,Any]]] but I am getting invalid cast compiler errors.
Any tips on how I can traverse and validate the name value at each level would be appreciated. I would preferably like to use the play json library
Issue was in the case class I was attempting to use. I wasn't accounting for the recursive nature of my Json structure
case class ActorTree(name : String, children:Seq[ActorTree] )