can I loop some data json with nested value - json

When I got a new data json ORDER_TRX_H_ID the result must looping with new ORDER_TRX_H_ID, but my result always show last data.
My code is
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataJSON := `[
{
"QUICK_DATA_H_ID": "1",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "FULLNAME",
"FIELD_ANSWER": "RUBEN",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "2",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "ALAMAT_KTP",
"FIELD_ANSWER": "jalandisana",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "3",
"ORDER_TRX_H_ID": "2",
"FIELD_QUESTION": "FULLNAME",
"FIELD_ANSWER": "Fariz",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "4",
"ORDER_TRX_H_ID": "2",
"FIELD_QUESTION": "ALAMAT_KTP",
"FIELD_ANSWER": "Bogor",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
}
]`
var data []map[string]interface{}
json.Unmarshal([]byte(dataJSON), &data)
qa := map[string]interface{}{}
for _, v := range data {
qa[v["FIELD_QUESTION"].(string)] = v["FIELD_ANSWER"]
}
hasil := data[0]
hasil["QUESTION"] = qa
delete(hasil, "FIELD_QUESTION")
delete(hasil, "FIELD_ANSWER")
hasilJSON, _ := json.MarshalIndent(hasil, "", " ")
fmt.Println(string(hasilJSON))
}
You can run my code
https://play.golang.org/p/aHUoYZlEQs4
My result always show last data
{
"DTM_CRT": "2019-08-28T16:25:15.757Z",
"ORDER_TRX_H_ID": "1",
"QUESTION": {
"ALAMAT_KTP": "Bogor",
"FULLNAME": "Fariz"
},
"QUICK_DATA_H_ID": "1"
}
my expected result
{
"DTM_CRT": "2019-08-28T16:25:15.757Z",
"ORDER_TRX_H_ID": "1",
"QUESTION": {
"ALAMAT_KTP": "jalandisana",
"FULLNAME": "RUBEN"
},
"QUICK_DATA_H_ID": "1"
},
{
"DTM_CRT": "2019-08-28T16:25:15.757Z",
"ORDER_TRX_H_ID": "2",
"QUESTION": {
"ALAMAT_KTP": "Bogor",
"FULLNAME": "Fariz"
},
"QUICK_DATA_H_ID": "2"
}

Why your result only showing 1 data? it because of this line of code:
hasil := data[0]
hasil will always have just one element
also qa will only contains value like this:
{
"ALAMAT_KTP": "BOGOR",
"FULLNAME": "Fariz"
}
it because every data iteration, qa[v["FIELD_QUESTION"].(string)] will keep replaced due to v["FIELD_QUESTION"].(string) is no unique, so in the 3rd iteration of data, the qa["ALAMAT_KTP] that already have value "jalandisana" is replaced with qa["ALAMAT_KTP] = "Bogor"
I modified your code here: https://play.golang.org/p/Ca4aGPGJwT7
I use 2 map[string]map[string]interface{} to hold qa and modified data
and then I combine them into one
package main
import (
"encoding/json"
"fmt"
)
func main() {
dataJSON := `[
{
"QUICK_DATA_H_ID": "1",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "FULLNAME",
"FIELD_ANSWER": "RUBEN",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "2",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "ALAMAT_KTP",
"FIELD_ANSWER": "jalandisana",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "3",
"ORDER_TRX_H_ID": "2",
"FIELD_QUESTION": "FULLNAME",
"FIELD_ANSWER": "Fariz",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "4",
"ORDER_TRX_H_ID": "2",
"FIELD_QUESTION": "ALAMAT_KTP",
"FIELD_ANSWER": "Bogor",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
}
]`
var data, finalResult []map[string]interface{}
json.Unmarshal([]byte(dataJSON), &data)
qa := map[string]map[string]interface{}{}
res := map[string]map[string]interface{}{}
for _, v := range data {
if qa[v["ORDER_TRX_H_ID"].(string)] == nil {
// initialize the map first if map is nil
qa[v["ORDER_TRX_H_ID"].(string)] = make(map[string]interface{})
}
qa[v["ORDER_TRX_H_ID"].(string)][v["FIELD_QUESTION"].(string)] = v["FIELD_ANSWER"]
delete(v, "FIELD_QUESTION")
delete(v, "FIELD_ANSWER")
// only assign res if res[key] is nil to prevent doubled data
if res[v["ORDER_TRX_H_ID"].(string)] == nil {
res[v["ORDER_TRX_H_ID"].(string)] = v
}
}
// combine qa and res in finalResult
for k, v := range res {
v["QUESTION"] = qa[k]
finalResult = append(finalResult, v)
}
hasilJSON, _ := json.MarshalIndent(finalResult, "", " ")
fmt.Println(string(hasilJSON))
}
Output:
[
{
"DTM_CRT": "2019-08-28T16:25:15.757Z",
"ORDER_TRX_H_ID": "1",
"QUESTION": {
"ALAMAT_KTP": "jalandisana",
"FULLNAME": "RUBEN"
},
"QUICK_DATA_H_ID": "1"
},
{
"DTM_CRT": "2019-08-28T16:25:15.757Z",
"ORDER_TRX_H_ID": "2",
"QUESTION": {
"ALAMAT_KTP": "Bogor",
"FULLNAME": "Fariz"
},
"QUICK_DATA_H_ID": "3"
}
]

Related

Best way to group two structs into a third one on Go

I have the following structs:
type A1 struct {
IdA1 string
NameA1 string
key string
}
type B1 struct {
IdB1 string
NameB1 string
Size string
key string
}
type C1 struct {
IdA1 string
Name string
B1Set B1
}
and I need to create a []struct of type C1, that holds a B1Set of B1, B1 is huge more than 2K entries and A1 is just 10 entries, a really slow and inefficient implementation would be to loop over A1, and ask if B1-key is equal to A1-key and store in a map the result, but.. is there any better way to implement this?
thanks in advance,
Add more info:
They are two different JSON files:
Json1:
[
{
"id": "device1",
"name": "dev1",
"pool": "pool1"
},
{
"id": "device2",
"name": "dev2",
"pool": "pool2"
}
...
]
And the other Json:
[
{
"name": "port1",
"size": 10,
"pool": "pool1",
"status": "active"
},
{
"name": "port2",
"size": 60,
"pool": "pool1",
"status": "active"
},
{
"name": "port3",
"size": 20,
"pool": "pool2",
"status": "down"
},
{
"name": "port8",
"size": 100,
"pool": "pool2",
"status": "active"
},
{
"name": "port10",
"size": 8000,
"pool": "pool1",
"status": "active"
},
...
]
So I need to create a new JSON file from those two with the following:
[
{
"id": "device1",
"name": "dev1",
"pool": "pool1",
"ports": [
{
"name": "port1",
"size": 10,
"pool": "pool1",
"status": "active"
},
{
"name": "port2",
"size": 60,
"pool": "pool1",
"status": "active"
},
{
"name": "port10",
"size": 8000,
"pool": "pool1",
"status": "active"
}
]
},
{
"id": "device2",
"name": "dev2",
"pool": "pool2",
"ports": [
{
"name": "port3",
"size": 20,
"pool": "pool2",
"status": "active"
},
{
"name": "port8",
"size": 100,
"pool": "pool2",
"status": "active"
}
]
}
]
taking into account that Json1 is not more than 10-12 entries and Json2 has more than 800-1000 entries.
So far:
read Json1 (devices), and Json2 (ports) and pass them into two []structs. Then:
results := make(map[string]*models.PortDevices}
portDevs := []models.PortDevices{}
for i := range devices {
results[devices[i].Pool] = &models.PortDevices{}
m := results[devices[i].Pool]
m.Id = devices[i].Id
m.Name = devices[i].Name
m.Pool = devices[i].Pool
m.Status = devices[i].Status
for p := range ports {
if val, ok := results[ports[p].Pool]; ok {
m := val
m.Ports = ports
}
}
portDevs = append(portDevs, *m)
}
devports := []models.PortDevices{}
for _, value := range results {
devports = append(devports, *value)
}
Is this what you are looking to do? https://play.golang.org/p/AZNzQAwRhN0
What this does is build a map grouping all of the ports by pool. Then it loops through what I labeled clusters and assigns the slice of Port to the matching Cluster by grabbing the matching slice by Pool value.
package main
import (
"encoding/json"
"fmt"
)
type Cluster struct {
ID string `json:"id"`
Name string `json:"name"`
Pool string `json:"pool"`
Ports []Port `json:"ports"`
}
type Port struct {
Name string `json:"name"`
Size int `json:"size"`
Pool string `json:"pool"`
Status string `json:"status"`
}
func main() {
var resources []Port
err := json.Unmarshal([]byte(resourceJSON), &resources)
if err != nil {
panic(err)
}
resourcesByPool := make(map[string][]Port)
for _, resource := range resources {
if _, ok := resourcesByPool[resource.Pool]; !ok {
resourcesByPool[resource.Pool] = []Port{}
}
resourcesByPool[resource.Pool] = append(resourcesByPool[resource.Pool], resource)
}
var clusters []Cluster
err = json.Unmarshal([]byte(clusterJSON), &clusters)
if err != nil {
panic(err)
}
for i := 0; i < len(clusters); i++ {
clusters[i].Ports = resourcesByPool[clusters[i].Pool]
}
out, err := json.MarshalIndent(clusters, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
var (
clusterJSON = `[
{
"id": "device1",
"name": "dev1",
"pool": "pool1"
},
{
"id": "device2",
"name": "dev2",
"pool": "pool2"
}
]`
resourceJSON = `[
{
"name": "port1",
"size": 10,
"pool": "pool1",
"status": "active"
},
{
"name": "port2",
"size": 60,
"pool": "pool1",
"status": "active"
},
{
"name": "port3",
"size": 20,
"pool": "pool2",
"status": "down"
},
{
"name": "port8",
"size": 100,
"pool": "pool2",
"status": "active"
},
{
"name": "port10",
"size": 8000,
"pool": "pool1",
"status": "active"
}]`
)

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)
}
}

Unmarshal deeply nested json in golang

I have an ugly way of unmarshalling the following json, but it requires much manual work. I am looking for a more programmatic way to obtain the various team names, if I didn't know how many teams exactly there were originally. It's truly one of the most poorly structured api's I've come across.
data := []byte(`{
"fantasy_content": {
"copyright": "Data provided by Yahoo! and STATS, LLC",
"league": [
{
"allow_add_to_dl_extra_pos": 0,
"current_week": "1",
"draft_status": "predraft",
"edit_key": "1",
"end_date": "2017-12-25",
"end_week": "16",
"game_code": "nfl",
"is_cash_league": "0",
"is_pro_league": "0",
"league_id": "XXXXX",
"league_key": "XXXX",
"league_type": "private",
"league_update_timestamp": null,
"name": "XXXXXX",
"num_teams": 14,
"renew": "XXXX",
"renewed": "",
"scoring_type": "head",
"season": "2017",
"short_invitation_url": "XXXXX",
"start_date": "2017-09-07",
"start_week": "1",
"url": "XXXXXX",
"weekly_deadline": ""
},
{
"teams": {
"0": {
"team": [
[
{
"team_key": "XXXX"
},
{
"team_id": "1"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"XXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXXX",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_commissioner": "1",
"manager_id": "1",
"nickname": "Andrew"
}
}
]
}
]
]
},
"1": {
"team": [
[
{
"team_key": "XXXXX"
},
{
"team_id": "2"
},
{
"name": "XXXXX"
},
[],
{
"url": "XXXXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "XXXX"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXX#yahoo.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "2",
"nickname": "Andrew"
}
},
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"is_comanager": "1",
"manager_id": "15",
"nickname": "XX"
}
}
]
}
]
]
},
"10": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "11"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XXX"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_01_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#gmail.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "11",
"nickname": "XX"
}
}
]
}
]
]
},
"2": {
"team": [
[
{
"team_key": "371.l.102542.t.3"
},
{
"team_id": "3"
},
{
"name": "XXX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/3"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/5603/30147468023_1c705edb29_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXXgmail.com",
"guid": "XXXX",
"image_url": "https://s.yimg.com/wv/images/6c93ed606f742d4c075bc091633cc072_64.jpg",
"manager_id": "3",
"nickname": "XX"
}
}
]
}
]
]
},
"3": {
"team": [
[
{
"team_key": "371.l.102542.t.4"
},
{
"team_id": "4"
},
{
"name": "XX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/4"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/dh/ap/fantasy/nfl/img/icon_10_100.png"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX#yahoo.com",
"guid": "XX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "4",
"nickname": "XX"
}
}
]
}
]
]
},
"8": {
"team": [
[
{
"team_key": "XXX"
},
{
"team_id": "9"
},
{
"name": "XxX"
},
[],
{
"url": "https://football.fantasysports.yahoo.com/f1/XX/9"
},
{
"team_logos": [
{
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/8393/28682944304_33bda49603_192sq.jpg?ct=fantasy"
}
}
]
},
[],
{
"waiver_priority": ""
},
{
"faab_balance": "100"
},
{
"number_of_moves": 0
},
{
"number_of_trades": 0
},
{
"roster_adds": {
"coverage_type": "week",
"coverage_value": "1",
"value": "0"
}
},
[],
{
"league_scoring_type": "head"
},
[],
[],
{
"has_draft_grade": 0
},
[],
[],
{
"managers": [
{
"manager": {
"email": "XXX",
"guid": "XXX",
"image_url": "https://s.yimg.com/wm/modern/images/default_user_profile_pic_64.png",
"manager_id": "9",
"nickname": "XXX"
}
}
]
}
]
]
},
"count": 14
}
}
],
"refresh_rate": "60",
"time": "110.55207252502ms",
"xml:lang": "en-US",
"yahoo:uri": "/fantasy/v2/league/XXXX/teams"
}
}`)
The following works, but it's a hassle and I have to hard code the different struct values per team, to get data for that team.
type TeamApi_ struct {
TeamKey string `json:"team_key"`
TeamId string `json:"team_id"`
Name string `json:"name"`
}
type LeaguesApi struct {
NumTeams int `json:"num_teams"`
TeamsApi struct {
Zero struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"0"`
One struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"1"`
Two struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"2"`
Three struct {
TeamsApi_ [][]TeamApi_ `json:"team"`
} `json:"3"`
} `json:"teams"`
}
type LeagueApiResult struct {
FantasyContent struct {
LeagueApi []LeaguesApi `json:"league"`
} `json:"fantasy_content"`
}
var Result LeagueApiResult
err := json.Unmarshal(data, &Result)
if err != nil {
fmt.Println(err)
}
fmt.Println(Result.FantasyContent.LeagueApi[1].TeamsApi.One.TeamsApi_[0][2].Name)
You probably want to use a custom JSON unmarshaller for this. You can see an example of how to use one here: http://choly.ca/post/go-json-marshalling/
Since the data is structured the way it is, with the teams section both containing teams and the count field, you'll likely need a fair bit of manual logic in there.
First, you can start by defining the League:
type League struct {
AllowAddToDlExtraPos int `json:"allow_add_to_dl_extra_pos,omitempty"`
CurrentWeek string `json:"current_week,omitempty"`
DraftStatus string `json:"draft_status,omitempty"`
EditKey string `json:"edit_key,omitempty"`
EndDate string `json:"end_date,omitempty"`
EndWeek string `json:"end_week,omitempty"`
GameCode string `json:"game_code,omitempty"`
IsCashLeague string `json:"is_cash_league,omitempty"`
IsProLeague string `json:"is_pro_league,omitempty"`
LeagueID string `json:"league_id,omitempty"`
LeagueKey string `json:"league_key,omitempty"`
LeagueType string `json:"league_type,omitempty"`
LeagueUpdateTimestamp interface{} `json:"league_update_timestamp,omitempty"`
Name string `json:"name,omitempty"`
NumTeams int `json:"num_teams,omitempty"`
Renew string `json:"renew,omitempty"`
Renewed string `json:"renewed,omitempty"`
ScoringType string `json:"scoring_type,omitempty"`
Season string `json:"season,omitempty"`
ShortInvitationURL string `json:"short_invitation_url,omitempty"`
StartDate string `json:"start_date,omitempty"`
StartWeek string `json:"start_week,omitempty"`
URL string `json:"url,omitempty"`
WeeklyDeadline string `json:"weekly_deadline,omitempty"`
Teams []Team `json:"-"`
}
Next, we can define the Team structure the way we want it to look.
type Team struct {
// Declare the fields of a Team
}
And finally, we declare a custom unmarshal function for the League.
func (l *League) UnmarshalJSON(data []byte) error {
type Alias League
aux := &struct {
*Alias
Teams map[string]interface{} `json:"teams"`
}{
Alias: (*Alias)(l),
}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
var teams []Team
for num, team := range aux.Teams {
// Add your code to parse each of the teams from the
// map you declared above.
}
l.Teams = teams
return nil
}
The unmarshal function will be called by Golangs json library automatically when it hits the League structure inside the LeagueApiResult.

How to parse JSON array data in Oracle APEX

I have following JSON output.I need to parse the data in to a table .Please help me the code.
{
"type": "Campaign",
"currentStatus": "Active",
"id": "206",
"createdAt": "1488438112",
"createdBy": "370",
"depth": "complete",
"folderId": "1428",
"name": "Car Loan",
"elements": [
{
"type": "CampaignAddToProgramBuilderAction",
"id": "1197",
"name": "Create Lead",
"memberCount": "0",
},
}
],
"isReadOnly": "false",
"runAsUserId": "372",
"actualCost": "2500.00",
"budgetedCost": "0.00",
"campaignCategory": "contact",
"campaignType": "GB",
"crmId": "",
"endAt": "1496289599",
"fieldValues": [
{
"type": "FieldValue",
"id": "8",
"value": "test"
},
{
"type": "FieldValue",
"id": "9",
"value": "APAC"
},
{
"type": "FieldValue",
"id": "11",
"value": ""
},
{
"type": "FieldValue",
"id": "12",
"value": "Direct Mail Campaigns"
},
{
"type": "FieldValue",
"id": "13",
"value": ""
}
],
"firstActivation": "1488439250",
"isEmailMarketingCampaign": "false",
"isIncludedInROI": "true",
}
I have to load the all the fields in to a table.following code is loading the data without nested fields,Please help to add "actual Cost" and field values(type,id,value)in below code.
declare
l_ws_response_clob CLOB;
l_ws_url VARCHAR2(500) := 'your URL';--above given the out put of JSON
l_list json_list;
l_obj json;
l_col1 VARCHAR2(100);
l_col2 VARCHAR2(100);
l_col3 VARCHAR2(100);
l_col4 VARCHAR2(100);
l_col5 VARCHAR2(100);
l_col6 VARCHAR2(100);
l_col7 VARCHAR2(100);
l_col8 VARCHAR2(100);
begin
--get JSON
apex_web_service.g_request_headers(1).name := 'Accept';
apex_web_service.g_request_headers(1).value := 'application/json; charset=utf-8';
apex_web_service.g_request_headers(2).name := 'Content-Type';
apex_web_service.g_request_headers(2).value := 'application/json; charset=utf-8';
l_ws_response_clob := apex_web_service.make_rest_request(
p_url => l_ws_url,
p_username => 'TEST',
p_password => 'TEST',
p_http_method => 'GET'
);
l_obj := json(l_ws_response_clob);
l_list := json_list(l_obj.get('elements'));
for i in 1..l_list.count LOOP
l_col1 := json_ext.get_string(json(l_list.get(i)),'type');
l_col2 := json_ext.get_string(json(l_list.get(i)),'currentStatus');
l_col3 := json_ext.get_string(json(l_list.get(i)),'folderId');
l_col4 := json_ext.get_string(json(l_list.get(i)),'name');
l_col5 := json_ext.get_string(json(l_list.get(i)),'id');
l_col6 := json_ext.get_string(json(l_list.get(i)),'createdAt');
l_col7 := json_ext.get_string(json(l_list.get(i)),'createdBy');
l_col8 := json_ext.get_string(json(l_list.get(i)),'isEmailMarketingCampaign');
--Actual cost and field values(type,id,value) needs to be added here which are in array list.Please help code here
INSERT INTO CAMPAIGN_TEST(RECORD_NUM,TYPE,CURRENT_STATUS,FOLDERID,NAME,ID,CREATEDAT,CREATEDBY,ISEMAILMARKETINGCAMPAIGN,) VALUES (i,l_col1,l_col2,l_col3,l_col4,l_col5,l_col6,l_col7,l_col8);
end LOOP;
end;
That's a pretty bad JSON you are dealing with there. Dangling commas (not allowed) and numbers stored as text instead of being delivered as numbers.
But that aside this is how you parse the data
declare
l_json varchar2 (32767) := '{"type": "Campaign","currentStatus": "Active","id": "206","createdAt": "1488438112","createdBy": "370",
"depth": "complete","folderId": "1428","name": "Car Loan", "elements": [ {
"type": "CampaignAddToProgramBuilderAction",
"id": "1197",
"name": "Create Lead",
"memberCount": "0"
}],
"isReadOnly": "false","runAsUserId": "372","actualCost": "2500.00","budgetedCost": "0.00","campaignCategory": "contact","campaignType": "GB",
"crmId": "","endAt": "1496289599","fieldValues": [ { "type": "FieldValue", "id": "8", "value": "test" },
{ "type": "FieldValue", "id": "9", "value": "APAC" },
{ "type": "FieldValue", "id": "11", "value": "" },
{ "type": "FieldValue", "id": "12", "value": "Direct Mail Campaigns" },
{ "type": "FieldValue", "id": "13", "value": "" }
],
"firstActivation": "1488439250","isEmailMarketingCampaign": "false","isIncludedInROI": "true"}';
l_number number;
begin
apex_json.parse (l_json);
--actualCost
l_number := to_number (apex_json.get_varchar2 ('actualCost'), '999999999990D00', 'NLS_NUMERIC_CHARACTERS=''.,''');
dbms_output.put_line ('Actual cost: ' || l_number);
-- fieldValues
for i in 1 .. apex_json.get_count ('fieldValues') loop
dbms_output.put_line ('Item number ' || i);
dbms_output.put_line (chr (9) || ' * Type: ' || apex_json.get_varchar2 ('fieldValues[%d].type', i));
dbms_output.put_line (chr (9) || ' * Id: ' || apex_json.get_varchar2 ('fieldValues[%d].id', i));
dbms_output.put_line (chr (9) || ' * Value: ' || apex_json.get_varchar2 ('fieldValues[%d].value', i));
end loop;
end;
Which then gives the output of:
Actual cost: 2500
Item number 1
* Type: FieldValue
* Id: 8
* Value: test
Item number 2
* Type: FieldValue
* Id: 9
* Value: APAC
Item number 3
* Type: FieldValue
* Id: 11
* Value:
Item number 4
* Type: FieldValue
* Id: 12
* Value: Direct Mail Campaigns
Item number 5
* Type: FieldValue
* Id: 13
* Value:
you may base your code with following code
instead of harcoded json you can send l_obj to xmltable function
then you can use insert to table
select T1.*,T2.*
from xmltable (
'/json'
passing apex_json.to_xmltype('
{
"type": "Campaign",
"currentStatus": "Active",
"id": "206",
"createdAt": "1488438112",
"createdBy": "370",
"depth": "complete",
"folderId": "1428",
"name": "Car Loan",
"elements": [{
"type": "CampaignAddToProgramBuilderAction",
"id": "1197",
"name": "Create Lead",
"memberCount": "0"
}],
"isReadOnly": "false",
"runAsUserId": "372",
"actualCost": "2500.00",
"budgetedCost": "0.00",
"campaignCategory": "contact",
"campaignType": "GB",
"crmId": "",
"endAt": "1496289599",
"fieldValues": [{
"type": "FieldValue",
"id": "8",
"value": "test"
}, {
"type": "FieldValue",
"id": "9",
"value": "APAC"
}, {
"type": "FieldValue",
"id": "11",
"value": ""
}, {
"type": "FieldValue",
"id": "12",
"value": "Direct Mail Campaigns"
}, {
"type": "FieldValue",
"id": "13",
"value": ""
}],
"firstActivation": "1488439250",
"isEmailMarketingCampaign": "false",
"isIncludedInROI": "true"
}
')
columns
type varchar2(1000) path '/row/type',
currentStatus varchar2(1000) path '/row/currentStatus',
folderId varchar2(1000) path '/row/folderId',
name varchar2(1000) path '/row/name',
id varchar2(1000) path '/row/id',
createdAt varchar2(1000) path '/row/createdAt',
createdBy varchar2(1000) path '/row/createdBy',
isEmailMarketingCampaign varchar2(1000) path '/row/isEmailMarketingCampaign',
actualCost varchar2(1000) path '/row/actualCost' ) T1,
xmltable (
'/json/fieldValues/row'
passing apex_json.to_xmltype('
{
"type": "Campaign",
"currentStatus": "Active",
"id": "206",
"createdAt": "1488438112",
"createdBy": "370",
"depth": "complete",
"folderId": "1428",
"name": "Car Loan",
"elements": [{
"type": "CampaignAddToProgramBuilderAction",
"id": "1197",
"name": "Create Lead",
"memberCount": "0"
}],
"isReadOnly": "false",
"runAsUserId": "372",
"actualCost": "2500.00",
"budgetedCost": "0.00",
"campaignCategory": "contact",
"campaignType": "GB",
"crmId": "",
"endAt": "1496289599",
"fieldValues": [{
"type": "FieldValue",
"id": "8",
"value": "test"
}, {
"type": "FieldValue",
"id": "9",
"value": "APAC"
}, {
"type": "FieldValue",
"id": "11",
"value": ""
}, {
"type": "FieldValue",
"id": "12",
"value": "Direct Mail Campaigns"
}, {
"type": "FieldValue",
"id": "13",
"value": ""
}],
"firstActivation": "1488439250",
"isEmailMarketingCampaign": "false",
"isIncludedInROI": "true"
}
')
columns
type varchar2(1000) path '/row/type',
id varchar2(1000) path '/row/id',
value varchar2(1000) path '/row/value'
) T2;

How can I add multiple parameters while posting using Swift

I have the following multiple json objects to post data using Alamofire. In which format I need to pass the parameters in swift. I am new to swift . Help me out.
{
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
"sandage": {
"bank": "",
"bag": ""
},
"inst": "",
"items": [{
"itemid": "606",
"qty": "1",
"sub": [{
"item": "1586",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1588",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1589",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1590",
"qty": "1",
"type": "addon",
"ext": ""
}]
}, {
"itemid": "639",
"qty": "1",
"sub": [{
"item": "1618",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1612",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1611",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1610",
"qty": "1",
"type": "addon",
"ext": ""
}]
}],
"discount": "0",
"coupon": [],
"delivery": "",
"user": {
"id": "13",
"fname": "Demo",
"lname": "Order",
"phone": "9876543210",
"dno": "",
"add1": "",
"add2": "",
"postcode": "",
"username": "demo#theepos.com",
"status": "1"
},
"otype": "1",
"ptype": "0",
"app_id": "A1A2A3A4",
"app_key": "K1K2K3K4",
"request": "placeorder"
}
I am using Alamofire to post the data..
var url: NSURL = NSURL(string: "http://\(platform).eposapi.co.uk")!
let params = [
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
.....
]
Alamofire.request(.POST, url, parameters: params, encoding: .JSON)
.responseJSON{ response in
if let result: AnyObject = response.result.value
{
let post: JSON = JSON(result)
}
}
Really thanks guys . I only followed the above commented instructions and got the answer. Help really appreciated
var url: NSURL = NSURL(string: "http://\(platform).eposapi.co.uk")!
let sandage = ["bank": "","bag": ""]
let sub_array = [ "item": "1586","qty": "1","type": "addon","ext": ""]
let items_array = ["itemid": "606","qty": "1","sub": sub_array ]
let user_Detail = ["id": "13","fname": "Demo","lname": "Order",
"phone": "9876543210","dno": "","add1": "",
"add2": "","postcode": "","username": "demo#theepos.com",
"status": "1"]
let params = [
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
"sandage": sandage,
"inst": "",
"items":items_array,
"discount": "0",
"coupon": [],
"delivery": "",
"user": user_Detail,
"otype": "1",
"ptype": "0",
"app_id": "A1A2A3A4",
"app_key": "K1K2K3K4",
"request": "placeorder"
]
Alamofire.request(.POST, url, parameters: params, encoding: .JSON)
.responseJSON{ response in
if let result: AnyObject = response.result.value
{
let post: JSON = JSON(result)
let status = post["status"].stringValue
let order_id = post["order_id"].stringValue
print(status)
print(order_id)