So this is my JSON:
{
"items": [{
"name": "Item 1",
"description": "This is Item 1",
"categories": ["Category1", "Category2", "Category3", "Category4"],
"size": ["M", "L"]
},{
"name": "Item 2",
"description": "This is Item 2",
"categories": ["Category1", "Category3", "Category4"],
"size": ["M"]
}]
}
I can read and print it perfectly fine
However, I want to change this structure to this one where each item is separated by category and size, and where the categories are used as keys.
{
"categories": {
"category1": [{
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
},{
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
},{
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
}...],
"category2": [{
...
}]
}
I've created the following data structure but I'm not quite sure how to continue:
struct Categories: Codable {
let category: String
let items: [Item]
struct Item: Codable {
let name, description, size: String
}
}
Is Codable the right solution for this? If so; how would I go on to achieve this?
For your current json you need
struct Root: Codable {
let categories: [String:[Item]]
}
struct Item: Codable {
let name, description, size: String
}
But I think it's better to make it like this
{
"category1": [{
"name": "Item 1",
"description": "This is Item 1",
"size": "M"
},{
"name": "Item 1",
"description": "This is Item 1",
"size": "L"
},{
"name": "Item 2",
"description": "This is Item 2",
"size": "M"
}],
"category2": [{
}]
}
Which will make you do this
let res = try? JSONDecoder().decode([String:[Item]].self,from:jsonData)
Without the Root struct and the useless categories key
Related
I´m working in back graphql API with Laravel and Lighthouse.
I have a table with a column named "config" that stores json data.
I´m trying to create a new register to that table.
I have a mutation:
createOrderTemplate(name: String!, config: JSON!): OrderTemplate #create
The schema is:
type OrderTemplate {
id: ID!
name: String!
config: JSON!
}
I´ve tried the mutation in graphql-playground
mutation{
createOrderTemplate(
name:"SomeName",
config:
[{
"w_name": "Name1",
"w_code": "001",
"place": "Place1",
"job": "job1",
"data": [
{
"name": "name1",
"quantity": 2
},
{
"name": "name2",
"quantity": 2
},
{
"name": "name3",
"quantity": 1
},
{
"name": "name4",
"quantity": 2
}
]
},
{
"w_name": "Name2",
"w_code": "002",
"place": "Place2",
"job": "job2",
"data": [
{
"name": "name1",
"quantity": 2
},
{
"name": "name2",
"quantity": 2
},
{
"name": "name3"
"quantity": 1
},
{
"name": "name4",
"quantity": 2
}
]
}]
){
id
name
config
}
When I typed this I get an error, all is colored red and it does not execute anything.
What am I doing wrong?
Firstly, try to run that query in Insomnia, so you could see the exception that is thrown.
Moreover, I don't think that config gets a valid JSON value. Try first with a simple JSON like {key: 'value'}
I have the following json which are nested. I am looking for the better approach to read the data. Below is the sample json
[
{
"id": 1,
"name": "some text",
"selections": [
{
"id": 38383,
"items": [
{
"type": "view",
"children": [
{
"nodeId": "groups",
"children": [
{
"nodeId": "groups 1",
"children": [
{
"type": "group level item",
"name": "text1",
"leaf": true,
"info": [
"groups ",
"groups 1",
"groups 2"
]
},
{
"type": "group level item",
"name": "text2",
"leaf": true,
"info": [
"groups ",
"groups 1",
"groups 2"
]
}
]
}
]
}
]
}
]
}
]
},
{
"id": 2,
"name": "some text",
"selections": [
{
"id": 23232,
"items": [
{
"type": "view",
"children": [
{
"nodeId": "Hirearchy",
"children": [
{
"nodeId": "Hirearchy level 1",
"children": [
{
"nodeId": "Hirearchy level 2",
"children": [
{
"type": "charactreistic value",
"name": "some text 1",
"leaf": true,
"info": [
"Hirearchy",
"Hirearchy level 1",
"Hirearchy level 2",
"Hirearchy level 3"
]
},
{
"type": "characterisitic value",
"name": "some text 2",
"leaf": true,
"info": [
"Hirearchy",
"Hirearchy level 1",
"Hirearchy level 2",
"Hirearchy level 3"
]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"id": 3,
"name": "some text",
"selections": [
{
"id": 2444,
"items": [
{
"type": "view",
"children": [
{
"nodeId": "category",
"children": [
{
"type": "some value",
"name": "some text 1",
"leaf": true,
"info": [
"category",
"category level 1"
]
},
{
"type": "some value",
"name": "some text 2",
"leaf": true,
"info": [
"category",
"category level 1"
]
}
]
}
]
}
]
}
]
},
{
"id": 4,
"name": "some text",
"selections": [
{
"id": 2444,
"items": [
{
"type": "view",
"children": []
}
]
}
]
},
{
"id": 5,
"name": "some text",
"selections": [
{
"id": 2444,
"items": []
}
]
},
{
"id": 6,
"name": "some text",
"selections": []
}
]
for id 1 - there is 3 levels of nesting and the last one has a property which says leaf = true. so in this i need to de structure the object to get the desire out put like
heading - group 2 (from info arrar)
name - ['text1', 'text2'] from the last leaf
for id 2 - there is 4 levels of nesting and the last one has a property which says leaf = true. so in this i need to de structure the object to get the desire out put like
heading - Hierarchy level 3
name - ['some text1', 'some text2']
for id 3 there is 2 levels of nesting and the last one has a property which says leaf = true. so i this
i need to se structure the object to get the desire output like this
heading - Category 1
name - ['some text 3', 'some text4']
for id 4 - there is 1 level of nesting but the array is blank
for id 5 - there is no nesting and the items array is blank
for id 6 - selections array is blank
Question 1. I need to write a generic method to loop thru the json object and find the node where the property 'leaf' is true.
Question 2. This generic method to work even if the nesting levels are 2 or 3 or 4 or it could be more also
Question 3. This generic method should not break the code when the array is empty also.
Requirement. this is required in angular 10 application where i need to destructure the object
Thanks in advance
My File looks like this
{
"Item Version": 1.0,
"Item Creation Time": "2019-04-14 14:15:09",
"Trade Dictionary": {
"Country": "India",
"TradeNumber": "1",
"action": {
"Action1": false
},
"Value": "XXXXXXXXXXXXXXX"
},
"Payments": {
"Payment Details": [{
"Payment Date": "2019-04-11",
"Payment Type": "Rej"
}]
}
}
I want the result in below format
Item Version,Item Creation Time,Trade Dictionary.Country,Trade Dictionary.TradeNumber,Trade Dictionary.TradeNumber.action.Action1,Trade Dictionary.TradeNumber.value,Payment.Payment Details.Payment Date,Payment.Payment Details.Payment Type
I'm creating a list of data from a JSON list from a website. However, URLSession.shared.dataTask is returning empty data.
I've tried printing outside the function of URLSession.shared.dataTask, JSONSerilization, JSONDecoder, Different forms of URLs
I've been working on this for almost a week and I still can't figure out what's the issue. My main guess right now is that it's because I'm printing inside the function, but from tutorials online I see that they all print inside.
Any help will be greatly appreciated! :)
if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!){
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
print("Data != Data")
return
}
let dataStr = String(decoding: data, as: UTF8.self)
print("DataStr" + dataStr) //Empty
do {
let dataParse = try? JSONDecoder().decode(OuterData.self, from: data)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(dataParse) //nil
print(json)//empty data
} catch let jsonError {
print ("jsonError")
print (jsonError)
}
}.resume()
//Created from https://app.quicktype.io/#l=go
struct Suggestion: Codable {
let id: String
let name: String
let audience_size: Int
let path = [String]()
let description: String?
let topic: Topic?
let disambiguation_category: String?
enum CodingKeys: String, CodingKey {
case id, name
case audience_size = "audience_size"
case path
case description = "description"
case topic
case disambiguation_category = "disambiguation_category"
}
}
struct OuterData: Codable{
let dataSuggestion: [Suggestion]
}
enum Topic: String, Codable {
case businessAndIndustry = "Business and industry"
case education = "Education"
case foodAndDrink = "Food and drink"
case hobbiesAndActivities = "Hobbies and activities"
case lifestyleAndCulture = "Lifestyle and culture"
case newsAndEntertainment = "News and entertainment"
case people = "People"
case shoppingAndFashion = "Shopping and fashion"
case sportsAndOutdoors = "Sports and outdoors"
case technology = "Technology"
case travelPlacesAndEvents = "Travel, places and events"
}
Expected Output:
{
"data": [
{
"id": "6008740787350",
"name": "Business and industry",
"audience_size": 1759626900,
"path": [
"Interests",
"Business and industry"
],
"description": ""
},
{
"id": "6003402305839",
"name": "Business",
"audience_size": 1231141110,
"path": [
"Interests",
"Business and industry",
"Business"
],
"description": "",
"topic": "Business and industry"
},
{
"id": "6003248297213",
"name": "Product (business)",
"audience_size": 935729470,
"path": [
"Interests",
"Additional Interests",
"Product (business)"
],
"description": null,
"topic": "Business and industry"
},
{
"id": "6004037932409",
"name": "Management",
"audience_size": 323096480,
"path": [
"Interests",
"Business and industry",
"Management"
],
"description": "",
"topic": "Business and industry"
},
{
"id": "6002840040679",
"name": "Music industry",
"audience_size": 251698230,
"path": [
"Interests",
"Additional Interests",
"Music industry"
],
"description": null,
"topic": "News and entertainment"
},
{
"id": "6002884511422",
"name": "Small business",
"audience_size": 87865033,
"path": [
"Interests",
"Business and industry",
"Small business"
],
"description": "",
"topic": "Business and industry"
},
{
"id": "6003165841322",
"name": "Distribution (business)",
"audience_size": 79327710,
"path": [
"Interests",
"Additional Interests",
"Distribution (business)"
],
"description": null,
"topic": "Business and industry"
},
{
"id": "6003342222945",
"name": "Show business",
"audience_size": 69642870,
"path": [
"Interests",
"Additional Interests",
"Show business"
],
"description": null,
"topic": "News and entertainment"
},
{
"id": "6002932439173",
"name": "Subscription business model",
"audience_size": 64490740,
"path": [
"Interests",
"Additional Interests",
"Subscription business model"
],
"description": null,
"topic": "Business and industry"
},
{
"id": "6003464157303",
"name": "Business Insider",
"audience_size": 62085690,
"path": [
"Interests",
"Additional Interests",
"Business Insider"
],
"description": null,
"topic": "Business and industry"
},
{
"id": "6003190330534",
"name": "Order (business)",
"audience_size": 60961920,
"path": [
"Interests",
"Additional Interests",
"Order (business)"
],
"description": null,
"topic": "Travel, places and events"
},
...
}
Simply replace
let dataSuggestion: [Suggestion]
with
let data: [Suggestion]
The names of the struct members must match the corresponding JSON keys unless you add CodingKeys.
And – as suggested in the comments – remove always the question mark in try? inside a do - catch block
OK, this is probably a REAL simple request.
But, I have 4 JSON files, well, I get JSON when doing a GET to a
//some IP address/some directory/some sub directory/name of folder
So I get back let's just say, NETWORKS, SITES, RESOURCES, COMPONENTS
Each one below NETWORKS is the CHILD...
Ok, next: I need to COMBINE these JSON files to populate JSTree (from jstree.com)
I have a basic JSON file like this and it WORKS beautifully:
(NOTE: the ID's below are irrelevant and DO NOT match in the REAL examples farther down here.)
The intent here is to JOIN all four JSON objects which I'm getting through a RESTful environment to JAVA API's that GET the data from the database.
[
{
"data": "Network 1",
"metadata": {"id" : "n1"},
"children": [ {
"data": "Site 1",
"metadata": {"id" : "s1"},
"children": [ {
"data": "Resource 1",
"metadata": {"id" : "r1"},
"children": [
{
"data": "Component 1",
"metadata": {"id" : "c1"}
},
{
"data": "Component 2",
"metadata": {"id" : "c2"}
},
{
"data": "Component 3",
"metadata": {"id" : "c3"}
} ] } ] },
"Site 2",
"Site 3",
"Site 4"]
}
]
Here's my dilemma:
I need to combine the following JSON files: SITES, RESOURCES, and COMPONENTS
Simple right? Not so much.
Here's a sample of each of the lower level JSON Objects:
NETWORKS:
[
{
"id": "23ef0d23-0d8d-4466-98da-81ef30791773",
"notes": "This is a network for network 1",
"name": "n1"
},
{
"id": "b4b46748-511a-49bf-9d22-8da014c76cc2",
"notes": "This is a network for network 2",
"name": "n2"
},
{
"id": "678b4a01-a6a6-449f-966d-c50c74964729",
"notes": "This is a network for network 3",
"name": "n3"
},
{
"id": "8e2822b1-49a8-498e-979b-2849cfa82148",
"notes": "This is a network for network 4",
"name": "n4"
}
]
SITES:
[
{
"id": "05683e7b-e471-4417-bead-317cfcbfaf30",
"name": "s1",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"notes": "This is site 1"
},
{
"id": "de8d654c-f9c4-4a4e-8742-32794b218b54",
"name": "s2",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"notes": "This is site 2"
},
{
"id": "16b2b1cf-2991-4717-ae65-2158700fa95d",
"name": "s3",
"networkId": "8e2822b1-49a8-498e-979b-2849cfa82148",
"notes": "This is site 3"
}
]
RESOURCES:
[
{
"id": "26db6a18-5099-4117-9adb-b8c808a3c478",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"siteId": "05683e7b-e471-4417-bead-317cfcbfaf30",
"name": "r1",
"notes": "This is Resource 1"
},
{
"id": "26ad2b53-f4b2-41c1-a618-d9e710452b7f",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"siteId": "05683e7b-e471-4417-bead-317cfcbfaf30",
"name": "r2",
"notes": "This is Resource 2"
}
]
And Finally, COMPONENTS:
[
{
"id": "6e8d13ad-9eb6-4213-bf84-a6e91d2e1460",
"resourceId": "26ad2b53-f4b2-41c1-a618-d9e710452b7f",
"siteId": "05683e7b-e471-4417-bead-317cfcbfaf30",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"name": "Component 1",
"notes": "This is my very first component - Yay!"
},
{
"id": "8f18cca3-378e-4f9b-8a39-eb2285fa61fd",
"resourceId": "26ad2b53-f4b2-41c1-a618-d9e710452b7f",
"siteId": "05683e7b-e471-4417-bead-317cfcbfaf30",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"name": "Component 2",
"notes": "This is my Second component - Yay!"
},
{
"id": "539370a6-577f-477d-a6ea-d45efd7e65aa",
"resourceId": "26ad2b53-f4b2-41c1-a618-d9e710452b7f",
"siteId": "05683e7b-e471-4417-bead-317cfcbfaf30",
"networkId": "23ef0d23-0d8d-4466-98da-81ef30791773",
"name": "Component 3",
"notes": "This is my Third component - Yay!"
}
]
Ultimately, when combined, it's GOT to look like the very first JSON example which WORKS for JSTree.
Thank you all for helping.
Regards