reformating cakephp find threaded - json

My goal is to use a tree object to store invoices. The issue I'm running into is that it always puts a "Invoice" model wrapper around each subsequent child. I tried just getting the results and using the Set class to clean up the redundant "Invoice", "children" but I couldn't figure out how to get it to work. I'm using this in an API so basically what I want to be able to do is move up and down the array without having to constantly do invoice.children.invoice.children
In my controller I have:
$results = $this->Invoice->find('threaded', array(
'order' => array('lft ASC') // or array('id ASC')
));
$this->set(array(
'results' => $results,
'_serialize' => 'results'
));
What I'm getting is:
{
"success": true,
"data": [
{
"id": 1,
"parent_id": null,
"lft": 1,
"rght": 30,
"name": "Invoices",
"children": [
{
"Invoice": {
"id": 2,
"parent_id": 1,
"lft": 2,
"rght": 15,
"text": "invoice 001"
},
"children": [
{
"Invoice": {
"id": 3,
"parent_id": 2,
"lft": 3,
"rght": 8,
"text": "invoice_item"
},
"children": [
{
"Invoice": {
"id": 4,
"parent_id": 3,
"lft": 4,
"rght": 5,
"text": "invoice_sub_item"
},
"children": []
},
{
"Invoice": {
"id": 5,
"parent_id": 3,
"lft": 6,
"rght": 7,
"text": "subitem#2"
},
"children": []
}
]
}
]
}
]
}
]
}
Ideally I'd like to have
invoices.invoice.text = "invoice 001"
and
invoices.invoice.invoice_item[0].text = "invoice_item"
Obviously I'll need to add/take away from the array and resubmit with changes. Is this possible or am I just making things harder on myself?

Related

How do I get back the value from one of the nested dictionary from JSON file

i am new to python and json. I have this issue where i am unable to get the values of 'labels' print out. It is under a nested dictionary 'result' .
Code that i have tried
for i in data['result']:
print("Value:", i['value'])
values = i['value']
print("X:", values['x'])
print("Y:", values['y'])
print("Width:", values['width'])
print("Height:", values['height'])
Output from the above code
However when i try to do print("labels:", values['labels'])
it return a keyerror: 'labels'
for item in values:
print(item)
this is the output shown
x
y
width
height
rotation
x
y
width
height
rotation
labels
May i ask how do i go out to print out the 'labels' value?
The json files is as follows:
{
"id": 9,
"created_username": "",
"created_ago": "3\u00a0weeks, 3\u00a0days",
"completed_by": {
"id": 1,
"first_name": "",
"last_name": "",
"email": ""
},
"task": {
"id": 1,
"data": {
"image": "/data/upload/2/adf8540d-2-33.png"
},
"meta": {},
"created_at": "2022-11-21T14:52:22.478537Z",
"updated_at": "2022-11-22T12:51:18.105745Z",
"is_labeled": true,
"overlap": 1,
"inner_id": 1,
"total_annotations": 1,
"cancelled_annotations": 0,
"total_predictions": 0,
"comment_count": 0,
"unresolved_comment_count": 0,
"last_comment_updated_at": null,
"project": 2,
"updated_by": 1,
"file_upload": 70,
"comment_authors": []
},
"result": [
{
"original_width": 512,
"original_height": 512,
"image_rotation": 0,
"value": {
"x": 50.898958419872464,
"y": 44.0069438675168,
"width": 2.397222452993284,
"height": 2.0975696463691196,
"rotation": 0
},
"id": "pgaiV8NjWC",
"from_name": "rect",
"to_name": "image",
"type": "rectangle",
"origin": "manual"
},
{
"original_width": 512,
"original_height": 512,
"image_rotation": 0,
"value": {
"x": 50.898958419872464,
"y": 44.0069438675168,
"width": 2.397222452993284,
"height": 2.0975696463691196,
"rotation": 0,
"labels" [
"LM"*
]
},
"id": "pgaiV8NjWC",
"from_name": "labels",
"to_name": "image",
"type": "labels",
"origin": "manual"
}
],
"was_cancelled": false,
"ground_truth": false,
"created_at": "2022-11-22T12:51:18.001777Z",
"updated_at": "2022-11-22T12:51:18.001777Z",
"lead_time": 21.556,
"project": 2,
"parent_prediction": null,
"parent_annotation": null
}
Use the json module
import json
dict = json.load(json_filename)
Then you should access the values by the dictionary keys. Be aware that the result value is a list. Therefore the index 1 is necessary.
values = dict['result'][1]['value']
print("X:", values['x'])

Angular 7 - How to display array inside of an object in HTML

I am trying to display array inside of an object in HTML. My sample JSON is like below...
I would like to display Product > ProductCategoryRelations > Category.Name in a string comma separeted like "Category 1, Category 2"
[
{
"Id": 2,
"Name": "Product 1",
"ProductCategoryRelations": [
{
"Id": 3,
"ProductId": 2,
"CategoryId": 2,
"Active": true,
"Category": {
"Id": 2,
"ParentId": 1,
"Name": "Category 1"
}
},
{
"Id": 4,
"ProductId": 2,
"CategoryId": 2,
"Active": true,
"Category": {
"Id": 2,
"ParentId": 1,
"Name": "Category 2"
}
}
],
How can I put all categories name in a string comma seperated?
What I have so fas is like below but it doesnt worrk
<dd class="col-sm-9" *ngFor="let category of product.ProductCategoryRelations">
<span>{{category.Name}}</span>
</dd>
In javascript, you would need this:
product.ProductCategoryRelations
.map(r => r.Category.Name)
.join(',')
to put it in context:
let product = {
"Id": 2,
"Name": "Product 1",
"ProductCategoryRelations": [
{
"Id": 3,
"ProductId": 2,
"CategoryId": 2,
"Active": true,
"Category": {
"Id": 2,
"ParentId": 1,
"Name": "Category 1"
}
},
{
"Id": 4,
"ProductId": 2,
"CategoryId": 2,
"Active": true,
"Category": {
"Id": 2,
"ParentId": 1,
"Name": "Category 2"
}
}
],
};
console.log(
product.ProductCategoryRelations
.map(r => r.Category.Name)
.join(',')
);
Now you can use .join(',') in Angular template syntax, but you cannot use the .map() bit. So I suspect the easiest way would be to add a utility function to your component that does this for you:
getCategoryNames(product) {
return product.ProductCategoryRelations.map(r => r.Category.Name);
}
and then do it in the template like this:
{{getCategoryNames(product).join(',')}}
If you need to do the same thing in multiple places in your app across multiple components, then I would recommend writing your own custom pipe.

Laravel pagination json format

I am using laravel database pagination for an api. It gives the output as follows :
{
"current_page": 1,
"data": [
{
"id": 1,
"name": "Default"
},
{
"id": 2,
"name": "Default without Sidebar"
}
],
"first_page_url": "http://example.com/api/layouts?a=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://example.com/api/layouts?a=1",
"next_page_url": null,
"path": "http://example.com/api/layouts",
"per_page": 10,
"prev_page_url": null,
"to": 2,
"total": 2
}
I don't want or need first_page_url, last_page_url, etc, so it should just be:
{
"current_page": 1,
"data": [
{
"id": 1,
"name": "Default"
},
{
"id": 2,
"name": "Default without Sidebar"
}
],
"from": 1,
"last_page": 1,
"to": 2,
"total": 2
}
So, Is there a way, to format the output json so that i can remove or hide some extra info which i don't need .
You can do something like this:
$except = ['first_page_url', 'last_page_url'];
return array_except(<YourModel>::paginate(...)->toArray(), $except);

Getting error while parsing json response from a dynamic {System.RuntimeType} variable

I'm working on some code in which uses dynamic variables jsonResponse .
dynamic jsonResponse = JsonConvert.DeserializeObject(response);
This variable contains collection of hotel list in json format. From this collection I am getting roomlist collection in a new variable roomResponseList :
var roomResponseList = jsonResponse["hotels"]["hotels"][rooms].roomResponseList;
I am getting first room detail into **JObject responseRateKeys **:
foreach (var roomByResponse in roomResponseList)
{
JObject responseRateKeys = JObject.Parse(roomByResponse.ToString());
var boardNameListByResponse = responseRateKeys.AsJEnumerable().AsEnumerable()
.Select(t => t["rates"]["boardName"].ToString().Trim())
.Distinct()
.ToList();
}
But when I am trying to get any item list from JObject by using linq lambda, I am getting error,
"Cannot access child value on Newtonsoft.Json.Linq.JProperty."
Value of roomByResponse=
{ "code": "DBL.KG-NM", "name": "DOUBLE KING BED NON SMOKING", "rates": [ { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|RO|IWH25|1~1~0||N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NRF", "rateType": "RECHECK", "net": "186.04", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "RO", "boardName": "ROOM ONLY", "cancellationPolicies": [ { "amount": "149.63", "from": "2017-07-14T03:29:00+05:30" } ], "rooms": 1, "adults": 1, "children": 0, "dailyRates": [ { "offset": 1, "dailyNet": "93.02" }, { "offset": 2, "dailyNet": "93.02" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|BB|IWB25|1~1~0||N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NOR", "rateType": "RECHECK", "net": "238.92", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "BB", "boardName": "BED AND BREAKFAST", "rooms": 1, "adults": 1, "children": 0, "dailyRates": [ { "offset": 1, "dailyNet": "119.46" }, { "offset": 2, "dailyNet": "119.46" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|RO|IWH25|2~2~1|2|N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NRF", "rateType": "RECHECK", "net": "372.06", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "RO", "boardName": "ROOM ONLY", "cancellationPolicies": [ { "amount": "299.25", "from": "2017-07-14T03:29:00+05:30" } ], "rooms": 2, "adults": 2, "children": 1, "childrenAges": "2", "dailyRates": [ { "offset": 1, "dailyNet": "186.03" }, { "offset": 2, "dailyNet": "186.03" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|BB|IWB25|2~2~1|2|N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NOR", "rateType": "RECHECK", "net": "477.84", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "BB", "boardName": "BED AND BREAKFAST", "rooms": 2, "adults": 2, "children": 1, "childrenAges": "2", "dailyRates": [ { "offset": 1, "dailyNet": "238.92" }, { "offset": 2, "dailyNet": "238.92" } ] } ] }
Thank you
Pravesh Singh
change linq to
responseRateKeys["rates"].AsJEnumerable().Select(t=>t["boardName"]).Distinct().ToList()

Query JSON in Postgres

I have some JSON in my postgres DB, it's in a table called site_content, the table has two rows, id and content, in content is where I store my JSON. I want to be able to find the a player given his id, my players are stored under the key series as this is the key needed to create my charts from JSON.
Here is the query I am currently using:
Blocking.get {
sql.firstRow("""SELECT * from site_content where content -> 'playersContainer' -> 'series' -> 'id' = ${id} """)
}.map { row ->
log.info("row is: ${row}")
if (row) {
objectMapper.readValue(row.getAt(0).toString(), Player)
}
}
}
However I get back this error:
org.postgresql.util.PSQLException: ERROR: operator does not exist:
json = character varying Hint: No operator matches the given name
and argument type(s). You might need to add explicit type casts.
Here is an example of my JSON:
"id": "${ID}",
"team": {
"id": "123",
"name": "Shire Soldiers"
},
"playersContainer": {
"series": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
{
"id": "2",
"name": "Pasty",
"teamName": "Shire Soldiers",
"ratings": [
6,
8,
9,
10
],
"assists": 25,
"manOfTheMatches": 32,
"cleanSheets": 2,
"data": [
3,
5,
7,
9,
10
],
"totalGoals": 24
}
]
}
I am using Groovy for this project, but I guess it's just the general JSON postgres syntax I am having problems with.
You're right, that's a problem with SQL syntax. Correct you query:
select * from json_test where content->'playersContainer'->'series' #> '[{"id":"1"}]';
Full example:
CREATE TABLE json_test (
content jsonb
);
insert into json_test(content) VALUES ('{"id": "1",
"team": {
"id": "123",
"name": "Shire Soldiers"
},
"playersContainer": {
"series": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
{
"id": "2",
"name": "Pasty",
"teamName": "Shire Soldiers",
"ratings": [
6,
8,
9,
10
],
"assists": 25,
"manOfTheMatches": 32,
"cleanSheets": 2,
"data": [
3,
5,
7,
9,
10
],
"totalGoals": 24
}
]
}}');
select * from json_test where content->'playersContainer'->'series' #> '[{"id":"1"}]';
About #> operator. This question might be also useful.
May be it could help: Into the sql statement, I added this 'cast' where I have the json field:
INSERT INTO map_file(type, data)
VALUES (?, CAST(? AS json))
RETURNING id
the datatype of 'data' into map_file table is: json