How to Access JSON Object contains json in Angular 2 - json

I want to show the data name, age, address in Angular2 DataTable or any other grid view controls in Angular2
[{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy",
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai",
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai",
}
}]
}];

Considering your question json as response
this.data = response[0].data;
<li *ngFor="let d of data">
{{d?.name}}
{{d?.age}}
{{d?.Address}}
</li>
In case your first array (json ) has multiple objects and then use nested ngFor

Pojo Classes
export class Data {
name: string;
age: string;
Address: string;
}
export class Datum {
id: string;
data: Data;
}
export class RootObject {
status: number;
message: string;
data: Datum[];
}
In Component.ts
export class AbcComponent implements OnInit {
a: any;
rootObj: RootObject = new RootObject();
constructor() { }
ngOnInit() {
this.a = [{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy",
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai",
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai",
}
}]
}]
this.rootObj = this.a;
console.log(this.rootObj.data[0].data.age)
}
}

In html :-
<table [mfData]="data[0].data" #mf="mfDataTable">
<tbody>
<tr *ngFor="let item of mf.data">
<td>{{item.data.name}}</td>
<td>{{item.data.Address}}</td>
<td>{{item.data.age}}</td>
<td>{{item.city | uppercase}}</td>
</tr>
</tbody>
</table>
In Component.ts :-
`data = [{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy"
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai"
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai"
}
}]`

Related

TypeScript convert json structure

I cant figure out how to make this conversion iterating a json.
I have this pojo in my backend:
class Part{
Long id;
String name;
Set<Part> parts = new HashSet<>();
}
Every part can have parts and this part more parts and so on.
I get this parts from httpclient in angular and get this json:
[{
"id": 1,
"name": "Parts A and B",
"parts": [{
"id": 2,
"name": "A",
"parts": [{
"id": 4,
"name": "A1",
"parts": []
}]
},
{
"id": 3,
"name": "B",
"parts": []
}
]
},
{
"id": 2,
"name": "A",
"parts": []
},
{
"id": 3,
"name": "B",
"parts": []
},
{
"id": 4,
"name": "A1",
"parts": []
}
]
And need to convert to this to populate a PrimeNG TreeTable:
{
"data": [{
"data": {
"name": "Parts A and B",
"id": "1"
},
"children": [{
"data": {
"name": "Part A",
"id": "2"
},
"children": [{
"data": {
"name": "A1",
"id": "4"
}
}]
},
{
"data": {
"name": "Part B",
"id": "3"
},
"children": []
}
]
},
{
"data": {
"name": "Part A",
"id": "2"
},
"children": []
},
{
"data": {
"name": "Part B",
"id": "3"
},
"children": []
},
{
"data": {
"name": "A1",
"id": "4"
},
"children": []
}
]
}
How can I do that?
In angular I get this in an array parts: Part[] and need partsTree: TreeNode[]
Thanks!!!
Its just a simple conversion by a map;
interface PartAPI{
id: number;
name: string;
parts : PartAPI[];
}
interface Data {
id: number;
name: string;
}
interface Part {
data : Data;
children : Part[];
}
console.log('a')
let convert = (inputArr: PartAPI[] = []) : Part[] => {
return inputArr.map(partApi => ({ data : { id : partApi.id , name : partApi.name }, children: convert(partApi.parts) }) as Part)
}
let data : PartAPI[] = [{
"id": 1,
"name": "Parts A and B",
"parts": [{
"id": 2,
"name": "A",
"parts": [{
"id": 4,
"name": "A1",
"parts": []
}]
},
{
"id": 3,
"name": "B",
"parts": []
}
]
},
{
"id": 2,
"name": "A",
"parts": []
},
{
"id": 3,
"name": "B",
"parts": []
},
{
"id": 4,
"name": "A1",
"parts": []
}
]
console.log(convert(data));

Cannot get array property by using Parse JSON groovy

I'm new to Groovy. But, I can try with some simple code lines to extract the data.
I have read the from Parse JSON using groovy script (using JsonSlurper). But it didn't help in my case.
My code line:
{
"errors": false,
"address_data": [
{
"address_id": "567",
"township": {
"id": "41079",
"name": "Test Data"
},
"city": {
"id": "1622",
"name": "Test City"
},
"region": {
"id": "663",
"name": "Metro Test"
},
"stock_source_code": "Test",
"is_default_address": false
},
{
"address_id": "45444",
"township": {
"id": "41079",
"name": "Test Test"
},
"city": {
"id": "1622",
"name": "Test City"
},
"region": {
"id": "663",
"name": "Metro Test Taguig"
},
"is_default_address": true
},
{
"address_id": "45444",
"township": {
"id": "888888",
"name": "Apas"
},
"city": {
"id": "432",
"name": "Test City"
},
"region": {
"id": "591",
"name": "Test Cebu"
},
"stock_source_code": "testce",
"is_default_address": false
}
]
}
My code lines:
def response = "data_above";
def object = new JsonSlurper().parseText(response);
def errors = object.errors
if (errors == false) { //could access object.errors property
log.info "Checking condition"
def addressData = object.address_data // Cannot get the data
}
How can I get the address_data property?

How to map Nested Array of Objects using Swift Object Mapper?

I am trying to map an array of objects using Object Mapper
I have this code so far, and my mapping is not successful
do {
if let data = data, let sectorData = Mapper<SubSectorsModel>().mapArrayOfArrays(JSONObject: try JSONSerialization.data(withJSONObject: data, options: [])) {
completionHandler(sectorData,(response as! HTTPURLResponse), error)
print("SectionData Received Successfully")
}
} catch {
completionHandler(nil,(response as! HTTPURLResponse), error)
print("Error parsing json get sector data: ", error.localizedDescription)
}
My Json data is as follows:
[
{
"SECTOR_NAME": "MANUFACTURERS",
"ID": "8",
"SECTOR": [
{
"ID": "144",
"NAME": "Biomass Processing"
},
{
"ID": "8",
"NAME": "Servicing engines and motors"
},
{
"ID": "23",
"NAME": "Furniture & fittings"
},
{
"ID": "31",
"NAME": "Fabrics & textiles"
},
{
"ID": "20",
"NAME": "Hand and machine tools"
},
{
"ID": "28",
"NAME": "Safety and security products"
},
{
"ID": "147",
"NAME": "Jewellery"
},
{
"ID": "156",
"NAME": "Beverages"
},
{
"ID": "165",
"NAME": "Stationery"
},
{
"ID": "9",
"NAME": "Industrial equipment"
},
{
"ID": "25",
"NAME": "Cleaning equipment"
},
{
"ID": "33",
"NAME": "Household consumer products"
},
{
"ID": "162",
"NAME": "Paper Products"
},
{
"ID": "170",
"NAME": "Memoribilia"
},
{
"ID": "143",
"NAME": "Food Products"
},
{
"ID": "22",
"NAME": "Automotive aviation marine and rail products"
},
{
"ID": "30",
"NAME": "Household appliances"
},
{
"ID": "151",
"NAME": "Iron Sheet"
},
{
"ID": "167",
"NAME": "Cosmetics"
},
{
"ID": "11",
"NAME": "Fuel Lubricants & Detergents"
},
{
"ID": "19",
"NAME": "Electrical appliances and equipment"
},
{
"ID": "27",
"NAME": "Packaging products"
},
{
"ID": "7",
"NAME": "Engines & parts"
},
{
"ID": "24",
"NAME": "Glass products"
},
{
"ID": "32",
"NAME": "Clothing & footwear"
},
{
"ID": "152",
"NAME": "Building Material"
},
{
"ID": "142",
"NAME": "Food Processing and Packaging"
},
{
"ID": "21",
"NAME": "Plastic products"
},
{
"ID": "29",
"NAME": "Pool & garden products"
},
{
"ID": "157",
"NAME": "Steel Products"
},
{
"ID": "138",
"NAME": "Optical Prescription Lenses"
},
{
"ID": "10",
"NAME": "Servicing & refurbishing"
},
{
"ID": "18",
"NAME": "Chemical"
},
{
"ID": "26",
"NAME": "Board paper and"
}
]
},
.
.
.
]
If you just want to send completionHandler anyway, use code below:
struct MyJsonStruct : Decodable {
struct SectorStruct : Decodable {
var ID : String
var NAME : String
}
var SECTOR_NAME : String
var ID : String
var SECTOR : [SectorStruct]
}
func handle(_ data : Data ) {
do {
let sectorData = try JSONDecoder().decode(MyJsonStruct.self, from: data) as MyJsonStruct
let yourArray = sectorData.SECTOR // if you need an array result
completionHandler(sectorData,(response as! HTTPURLResponse), error)
print("SectionData Received Successfully")
} catch {
completionHandler(nil,(response as! HTTPURLResponse), error)
print("Error parsing json get sector data: ", error.localizedDescription)
}
}

How to exclude specific fields from JSON using groovy

I would like to exclude the items which don't have productModel property in the below JSON. How can we achieve this in groovy
I tried using hasProperty but not worked for me as expected. If possible can I get some sample snippet
I tried below code - but didn't work as I expected.
response.getAt('myData').getAt('data').getAt('product').hasProperty('productModel').each { println "result ${it}" }
Any help would be really appreciated.
{
"myData": [{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "Macbook"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
}
],
"metadata": {
"count": 3,
"offset": 0
}
}
If you want to exclude specific fields from JSON object then you have to recreate it using filtered data. The crucial part takes these two lines (assuming that json variable in the below example stores your JSON as text):
def root = new JsonSlurper().parseText(json)
def myData = root.myData.findAll { it.data.product.containsKey('productModel') }
What happens here is we access root.myData list and we filter it using findAll(predicate) method and predicate in this case says that only objects that have key productModel in path data.product are accepted. This findAll() method does not mutate existing list and that is why we store the result in variable myData - after running this method we will end up with a list of size 2.
In next step you have to recreate the object you want to represent as a JSON:
def newJsonObject = [
myData: myData,
metadata: [
count: myData.size(),
offset: 0
]
]
println JsonOutput.prettyPrint(JsonOutput.toJson(newJsonObject))
In this part we create newJsonObject and in the end we convert it to a JSON representation.
Here is the full example:
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
def json = '''{
"myData": [{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "Macbook"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {}
}
],
"metadata": {
"count": 3,
"offset": 0
}
}'''
def root = new JsonSlurper().parseText(json)
def myData = root.myData.findAll { it.data.product.containsKey('productModel') }
def newJsonObject = [
myData: myData,
metadata: [
count: myData.size(),
offset: 0
]
]
println JsonOutput.prettyPrint(JsonOutput.toJson(newJsonObject))
And here is the output it produces:
{
"myData": [
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "6s"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [
{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {
}
},
{
"data": {
"product": {
"productId": "apple",
"productName": "iPhone",
"productModel": "7"
},
"statusCode": "active",
"date": "2018-08-07T00:00:00.000Z"
},
"links": [
{
"productUrl": "test"
},
{
"productImage": "test"
}
],
"info": {
}
}
],
"metadata": {
"count": 2,
"offset": 0
}
}

parse nested json to backbone collections

I'm just starting with Backbone and I'm running into a problem. I have a nice restful setup. For most of my GET request I receive a single collection of models, but for one I am loading nested relational data, which creates nested JSON.
In Backbone I have the following Models:
App.Models.Sequence = Backbone.Model.extend({});
App.Models.Layer = Backbone.Model.extend({});
App.Models.Item = Backbone.Model.extend({});
and these collections
App.Collections.Sequences = Backbone.Collection.extend({
model: App.Models.Sequence,
url: '/api/sequences/'
});
App.Collections.Layers = Backbone.Collection.extend({
model: App.Models.Layer,
url: '/api/layers'
});
App.Collections.Items = Backbone.Collection.extend({
model: App.Models.Item,
url: '/api/items'
});
I load data as JSON:
[
{
"id": "1",
"project_id": "8",
"name": "Seq1",
"layers": [
{
"id": "1",
"name": "Layer11",
"sequence_id": "1",
"items": [
{
"id": "1000000",
"layer_id": "1",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000001",
"layer_id": "1",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000002",
"layer_id": "1",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000003",
"layer_id": "1",
"itemtype_id": "4",
"position": "0"
}
]
},
{
"id": "2",
"name": "Layer12",
"sequence_id": "1",
"items": [
{
"id": "1000004",
"layer_id": "2",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000005",
"layer_id": "2",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000006",
"layer_id": "2",
"itemtype_id": "3",
"position": "0"
},
{
"id": "1000007",
"layer_id": "2",
"itemtype_id": "4",
"position": "0"
}
]
},
{
"id": "3",
"name": "Layer13",
"sequence_id": "1",
"items": [
{
"id": "1000008",
"layer_id": "3",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000009",
"layer_id": "3",
"itemtype_id": "4",
"position": "0"
},
{
"id": "1000010",
"layer_id": "3",
"itemtype_id": "5",
"position": "0"
}
]
}
]
},
{
"id": "2",
"project_id": "8",
"name": "Seq2",
"layers": [
{
"id": "4",
"name": "Layer21",
"sequence_id": "2",
"items": []
},
{
"id": "5",
"name": "Layer22",
"sequence_id": "2",
"items": []
}
]
},
{
"id": "3",
"project_id": "8",
"name": "Seq3",
"layers": [
{
"id": "6",
"name": "Layer31",
"sequence_id": "3",
"items": []
},
{
"id": "7",
"name": "Layer32",
"sequence_id": "3",
"items": []
}
]
}
]
How can I get Sequences, Layers and Items into my collections?
You can use a combination of underscore's flatten and pluck to do this neatly:
var data = { /* your JSON data */ };
var allSequences = _.clone(data);
var allLayers = _.flatten(_.pluck(allSequences, 'layers'));
var allItems = _.flatten(_.pluck(allLayers, 'items'));
var sequences = new App.Collections.Sequences(allSequences);
var layers = new App.Collections.Layers(allLayers);
var items = new App.Collections.Items(allItems);
If you don't want Sequences and Layers to contain their child objects, override Model.parse to trim them. For example:
App.Models.Sequence = Backbone.Model.extend({
parse: function(attrs) {
delete attrs.layers;
return attrs;
}
});
And initialize/add the collection with the parse:true option:
var sequences = new App.Collections.Sequences(allSequences, {parse:true});
Et cetera.