La codifica JSON out of the box in Go è davvero bella, ma ho bisogno di ottenere l'output per abbinare un determinato formato aggiungendo un livello. Ho capito un modo, ma speravo che ci sarebbe stato un modo più semplice di come lo sto facendo io.C'è un modo più semplice per aggiungere un livello su un oggetto JSON usando la codifica Golang JSON?
Di seguito è riportato un esempio di come lo sto facendo.
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
)
type Query struct {
XMLName xml.Name `xml:"http://marklogic.com/appservices/search query" json:"-"`
Format int `xml:"-" json:"-"`
Queries []interface{} `xml:",any" json:"queries"`
}
type TermQuery struct {
XMLName xml.Name `xml:"http://marklogic.com/appservices/search term-query" json:"-"`
Terms []string `xml:"http://marklogic.com/appservices/search text" json:"text"`
Weight float64 `xml:"http://marklogic.com/appservices/search weight,omitempty" json:"weight,omitempty"`
}
// use fakeQuery to avoid an infinite loop
type fakeQuery Query
//MarshalJSON for Query struct in a special way to add wraping {"query":...}
func (q Query) MarshalJSON() ([]byte, error) {
return wrapJSON(`query`, fakeQuery(q))
}
// use fakeTermQuery to avoid an infinite loop
type fakeTermQuery TermQuery
//MarshalJSON for TermQuery struct in a special way to add wraping {"term-query":...}
func (q TermQuery) MarshalJSON() ([]byte, error) {
return wrapJSON(`term-query`, fakeTermQuery(q))
}
func wrapJSON(name string, item interface{}) ([]byte, error) {
var buffer bytes.Buffer
b, err := json.Marshal(item)
buffer.Write([]byte(`{"`))
buffer.Write([]byte(name))
buffer.Write([]byte(`":`))
buffer.Write(b)
buffer.Write([]byte(`}`))
return buffer.Bytes(), err
}
Ho un sacco di strutture definite che avrei bisogno di fare questo per, quindi spero in una soluzione migliore che non mi lascerà con con 100 linee di codice per aggiungere solo un wrapper intorno all'oggetto JSON. Idealmente mi piacerebbe qualcosa che possa raggiungere il massimo con il nome dell'elemento XML definito per l'encoder XML e utilizzarlo per avvolgere il JSON.
Nel mio caso sto utilizzando le funzioni MarshalJSON perché queste strutture possono essere annidate. Se aiuta, so sempre che la struttura della query è la struttura principale.
Questo è molto vicino. Sfortunatamente ho le situazioni in cui queste strutture sono annidate. Quindi un output di esempio è '{" query ": {" query ": [{" term-query ": {" testo ": [" dati "]}}]}}'. Questo è il motivo per cui utilizzo le funzioni MarshalJSON. – justdewit
@justdewit Visualizza la risposta modificata. Fammi sapere se questo affronta la tua domanda originale in modo più accurato. – sberry
Grazie! Molto meglio di quello che stavo facendo. – justdewit