Reverse JSON Grails/Groovy - json

I have a JSON which looks like :
[
{ Name: "mike",
Address: "xyz"
Parent: {
NAme: "john"
Address: "xyz"
Parent: {
NAme: "Ross"
Adress: "asdsa"
}
}
]
I want to reverse it such that it looks like :
[
{ Name: "Ross",
Address: "adsad"
child: {
NAme: "john"
Address: "xyz"
child: {
NAme: "Mike"
Adress: "xyz"
}
}
]
What would be the best way to reverse this using (something generic i.e. the json can be much bigger with more parent objects)?

Related

How can I store my data into the MongoDB?

I am trying to download stock data using Alpha Vantage API. I send a request and after some work on responded data I have an array like below:
[
{
id: "MSFT",
stockData: [
{ date: "1634601600", summary: [Object] },
{ date: "1634688000", summary: [Object] } ]
}
]
And [Object] is something like:
{
date: "1646956800",
summary: { open: 287.96, high: 289.51, low: 279.43, close: 280.07, volume: 27209330 }
}
But I don't know how can I save it into the MongoDB? I could save a simpler structure and I knew I must create a class with the same property names as the response JSON, then instantiate the class and assign the properties of the response value to the properties of the class instance then save it to the database.
But now I am a little confused and don't know how properly deal with this. Also what if I have an array with more nested values of different size like below:
[
{
id: "AAPL",
stockData: [
{ date: 1634601600, summary: [Object] },
{ date: 1634688000, summary: [Object] },
{ date: 1634774400, summary: [Object] },
{ date: 1634860800, summary: [Object] }
]
},
{
id: "MSFT",
stockData: [
{ date: 1634601600, summary: [Object] },
{ date: 1634688000, summary: [Object] }
]
}
]

How to map an object from JSON file to another object?

Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.

Converting json object to typescript interface causing error in the mock object while unit testing in Angular 11

I am receiving a json response in an Angular 11 app and I have created an interface corresponding to that json object. The json object is
{
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
The typescript interface I created for this json object is
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface Division {
division: Division;
}
I am using a service division.sevice.ts to fetch the above json response from API and everything works fine. I am trying to write unit tests for the this service in the division.service.spec.ts file. I created a mockDivisionObj inside this file for testing purpose which is shown below.
mockDivisionObj = {
"division": {
"uid": "f5a10d90-60d6-4937-b917-1d809bd180b4",
"name": "Sales Division",
"title": "Sales",
"type": "Form",
"formFields": [
{
"id": 1,
"name": "firstName",
"label": "First Name",
"value": "John"
},
{
"id": 2,
"name": "lastName",
"label": "Last Name",
"value": "Smith"
}
]
}
}
An error is shown which says
Property 'division' is missing in type '{ uid: string; name: string; title: string; type:
string; formFields: { id: number; name: string; label: string; value: string; }[]; }' but
required in type 'Division'.
I think the way I created the interface may be wrong but I couldn't figure out what exactly is causing the issue. Please help me out with this.
I was able to fix the issue by changing the name of one of the interfaces in the file to 'AppDivision' as shown below.
export interface FormField {
id: number;
name: string;
label: string;
value: string;
}
export interface Division {
uid: string;
name: string;
title: string;
type: string;
formFields: FormField[];
}
export interface AppDivision {
division: Division;
}
The same name for two interfaces caused the error in the unit test mock object.
Your code is fine.To solve this error you can try the code below =>
this.division = this.mockDivisionObj.division as Division;
Check the Link: StackBlitz Demo link.

mongodb $lookup has_many association from embedded document

I have a boards collection, a lists collection, and a cards collection. An array of lists is embedded in a board document. I am trying to get an output that looks like this:
{
_id: 1,
title: "a board",
lists: [
{
_id: 1,
title: "a list",
cards: [ { _id: 1, title: "a card", list_id: 1 }, { _id: 2, title: "another card", list_id: 1 } ]
},
...
]
}
I want to nest the cards in the list it belongs to. The card document has a list_id field. I tried this:
db.boards.aggregate([
{ '$match' => { _id: 1 } },
{ '$lookup' => {
from: "cards",
localField: "lists._id",
foreignField: "list_id",
as: "cards"
} },
])
But that resulted in:
{
_id: 1,
title: "a board",
lists: [ { _id: 1, title: "a list" } ],
cards: [ { _id: 1, title: "a card", list_id: 1 }, { _id: 2, title: "another card", list_id: 1 } ]
}
I know that I have to use $unwind to get the result I want, but I can't get it to work
You need one additional aggregation pipeline step to "merge" these two lists and you can achieve it by running $map with embedded $filter. It simply works as a "join" operation on two arrays:
{
$project: {
_id: 1,
title: 1,
lists: {
$map: {
input: "$lists",
as: "list",
in: {
$mergeObjects: [
"$$list",
{
cards: {
$filter: {
input: "$cards",
cond: { $eq: [ "$$this.list_id", "$$list._id" ] }
}
}
}
]
}
}
}
}
}
Mongo Playground

Json error - Cannot access child value on newtonsoft.json.linq.jproperty.

I have the following Json -
Property {
id: 122334,
source:
[ id : 123,
address:
{
city: "little rock",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 222,
name: "The wall",
count: 2
}, ]
[ {id: 8889,
address:
{
city: "milka",
state: "Arkansas",
country: "USA"
},
unit:
{
id: 555,
name: "The watt",
count: 3
},
},
]
}
I am parsing it the following way -
string data = client.DownloadString(URL);
JToken token = JObject.Parse(data);
if (!string.IsNullOrEmpty(Convert.ToString(token["property"].Children())))
{
token["property"].Children().ToList().ForEach(child =>
{
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
if (GetID == id)
{
//move rest of the code here
}
else
{
}
});
}
But I get the execption - cannot access child value on newtonsoft.json.linq.jproperty.
at the line -
string GetID = Convert.ToString(child["source"]["unit"]["id"]);
What am I doing wrong?
enter code here