Go structure for unmarshalling a JSON array - json

So I have some JSON (courtesy of the PetFinder API) that has a JSON array "pet". I want to unmarshal from it, using the "encoding/json" package, a slice of pet structs. What would this kind of structure look like? I can't find any examples of how the unmarshall function handles JSON arrays.
Here's what I was planning to do once I had a proper struct:
pfetch := new(PetsFetcher) // where PetsFetcher is the struct im asking for
err := json.Unmarshal(body, &pfetch)
And here's the json that is in body (in the form of a slice of ascii bytes):
{
"petfinder": {
"lastOffset": {
"$t": 5
},
"pets": {
"pet": [
{
"options": {
"option": [
{
"$t": "altered"
},
{
"$t": "hasShots"
},
{
"$t": "housebroken"
}
]
},
"breeds": {
"breed": {
"$t": "Dachshund"
}
}
},
{
"options": {
"option": {
"$t": "hasShots"
}
},
"breeds": {
"breed": {
"$t": "American Staffordshire Terrier"
}
},
"shelterPetId": {
"$t": "13-0164"
},
"status": {
"$t": "A"
},
"name": {
"$t": "HAUS"
}
}
]
}
}
}
Thanks in advance.

I really have no idea what those $t attributes are doing there in your JSON, so let’s answer your question with a simple example. To unmarshal this JSON:
{
"name": "something",
"options": [
{
"key": "a",
"value": "b"
},
{
"key": "c",
"value": "d"
},
{
"key": "e",
"value": "f"
},
]
}
You need this Data type in Go:
type Option struct {
Key string
Value string
}
type Data struct {
Name string
Options []Option
}

You can unmarshal a javascript array into a slice. The marhsal/unmarshalling rules are described under Marshal in the json package.
To unmarshal keys that look like "$t", you'll have to annotate the struct that it'll unpack into.
For example:
type Option struct {
Property string `json:"$t,omitempty"`
}
It may be that the $t that appear are a mistake, and are supposed to be keys in a dictionary.

Related

Golang iterate over nested struct

i want to iterate over a nested json struct in golang. The issue is, i do not exactly know how nested the structure will be, becuase there are multiple jsons. In this case for example the output should be:
"available": false
"type": "foo"
"name": "foo"
"street": "foo"
....
Is that possible?
{
"informations": {
"available": false,
"provide": {
"informations": {
"customer": {
"type": "foo",
"address": {
"name": "foo",
"street": "foo",
"zipcode": "123",
"city": "foo"
}
}
}
}
}
}
I think you can do this with a map[string]interface{}. Because, as you said that you don't know exactly the structure of the JSON. But, again, you need to know the JSON structure each time while extracting data. Also, you need to do type assertion for inner map[string]interface{}. You can look at the answer from here for type assertion.
Here's the example code that I wrote:
package main
import (
"encoding/json"
"fmt"
)
var j = `{
"informations": {
"available": false,
"provide": {
"informations": {
"customer": {
"type": "foo",
"address": {
"name": "foo",
"street": "foo",
"zipcode": "123",
"city": "foo"
}
}
}
}
}
}`
func main() {
var data map[string]interface{}
err := json.Unmarshal([]byte(j), &data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(data["informations"])
information := data["informations"]
provide := information.(map[string]interface{})["provide"]
fmt.Println(provide)
}
Output will be:
map[available:false provide:map[informations:map[customer:map[address:map[city:foo name:foo street:foo zipcode:123] type:foo]]]]
map[informations:map[customer:map[address:map[city:foo name:foo street:foo zipcode:123] type:foo]]]
Go Playground

How to create hierarchical json structure by slice string path

I'm building a backend for a file manager written in Go.
I'm looking for a way to make an example slice string path.
sliceStr := []string{
"/file_A.txt",
"/folder_B/file_B.txt",
"/folder_C/sub_folder_C/file_C.txt",
"/folder_C/sub_folder_C/file_C_2.txt",
}
to create an api that returns a hierarchical json structure to pass to the frontend using Devextreme FileManager. Like below
[
{
"name": "file_A.txt",
"isDirectory": false
},
{
"name": "folder_B",
"isDirectory": true,
"items": [
{
"name": "file_B.txt",
"isDirectory": false
}
]
},
{
"name": "folder_C",
"isDirectory": true,
"items": [
{
"name": "sub_folder_C",
"isDirectory": true,
"items": [
{
"name": "file_C.txt",
"isDirectory": false,
},
{
"name": "file_C_2.txt",
"isDirectory": false
}
]
}
]
}
]
you can try this method
join the slice into a byte array
Implement you own json UnmarshalJSON
type Yourstruct struct {
.......
}
func (t *Yourstruct ) UnmarshalJSON(data []byte) error
demo case

Presto Json Parsing

I have a json field(attached sample) and i need to extract the values in ProvisioningSystem path but it works only if i hardcode the array location.How can i extract the value without hardcoding ?Thanks in Advance!
Code:
TRANSFORM(CAST(JSON_EXTRACT(order_json, '$.Order.Accounts.Account') AS ARRAY), x -> JSON_EXTRACT_SCALAR(x,'$.ProvisioningSystems.ProvisioningSystem[1].SystemName'))
Json:
{
"Order":
{
"Accounts": {
"Account": [
{
"ProvisioningSystems": {},
},
{
"ProvisioningSystems": {
"ProvisioningSystem": [
{
"SystemOrderRef": "12345",
"SystemName": "Testsystem",
"SystemOrderRefType": "Provision"
}
]
},
}
]
},
}
}
}

How to create correct struct for json

how to parse json correctly I have the following json file
{
"hello": {
"title": "Golang",
"story": [
"Go lang story",
"Channel story"
],
"options": [
{
"text": "That story",
"arc": "west"
},
{
"text": "Gee",
"arc": "east"
}
]
},
"world": {
"title": "Visiting",
"story": [
"Boo",
"Doo",
"Moo",
"Qoo"
],
"options": [
{
"text": "weird",
"arc": "west"
},
{
"text": "funny",
"arc": "north"
}
]
}
}
I've created these structs for the inner part
type chapter struct{
Title string `json:"title"`
Story []string `json:"story"`
Option []option `json:"options"`
}
type option struct {
Text string `json:"text"`
Arc string `json:"arc"`
}
but I don't know how to parse wrappers like "hello" and "world"
All you need to do structuring the root map.
{
"hello":{},
"world":{}
}
Here the hello and world is also inside a map. So you need to structure them too.
var root map[string]chapter
json.Unmarshal(JSONDATA,&root)
Playground example: https://play.golang.org/p/VZ9Bn215dDW

RestKit mapKeyOfNestedDictionaryToAttribute with array

I have a JSON response which looks like the sample below. I have added some comments // to emphasize my question.
I have no idea how to build the RKObjectMapping for the dynamic keys ("FieldNameA", "FieldNameB" - this could be anything) in combination with the array as the value. Each item of the array is of a type FieldResult.
I already learned how to handle varying key names here, but I don't get how I could properly map the array item type.
{
"result": {
"status": "FAILURE",
"details": {
"FieldNameA": [ // dynamic key name here, array of objects as a value
{
"details": {
"errorName": "InvalidField",
"errorNumber": 123
},
"status": "FAILURE"
}
],
"FieldNameB": [ // multiple values in this array, all of same type FieldResult
{
"details": {
"errorName": "UpdateRequired",
"errorNumber": 321
},
"status": "UPDATE_REQUIRED",
"suggestion": {
"update": "UpdatedInputValue"
}
},
{
"details": {
"errorName": "TooShort",
"errorNumber": 1
},
"status": "FAILURE"
}
]
}
}
}
Any help appreciated!