How to concatenate variable value into the byte key values ?
type Result struct {
SummaryID int `json:"summaryid"`
Description string `json:"description"`
}
byt := []byte(`
{
"fields": {
"project":
{
"key": "DC"
},
"summary": "Test" + Result.SummaryID,
"description": Result.Description,
"issuetype": {
"name": "Bug"
}
}
}`)
Note: values of Result.SummaryID and Result.Description return from the db.Query() and rows.Scan().
Go doesn't support string interpolation, so you'll have to use something like fmt.Sprintf or the template package if you want to compose strings out of smaller substrings.
You can do the former like so:
var buf bytes.Buffer
byt := []byte(fmt.Sprintf(`
{
"fields": {
"project":
{
"key": "DC"
},
"summary": "Test%d",
"description": "%s",
"issuetype": {
"name": "Bug"
}
}
}`, result.SummaryID, result.Description))
Though I would really advise against it, since the encoding/json package is designed for safely and sanely outputting JSON strings.
Here's an example that uses struct embedding for the main object, and maps elsewhere to demonstrate both approaches.
type WrappedResult struct {
Project map[string]string `json:"project"`
Result
IssueType map[string]string `json:"issuetype"`
}
byt, err := json.MarshalIndent(map[string]interface{}{
"fields": WrappedResult{
Result: result,
Project: map[string]string{ "key": "DC" },
IssueType: map[string]string{ "name": "Bug" },
},
});
(note that your type declaration contradicts your JSON example in that the former specifies summaryid but the latter has summary)
Related
I need to marshal/unmarshal json to struct in golang. Assume the struct is
type A struct {
Id string `json:"id"`
Version string `json:"version"`
Actors []actor `json:"actors`
Payload struct {
Name string `json:"name"`
Number string `json:"number"`
}
}
type payload struct {
Name string `json:"name"`
Number string `json:"number"`
}
type actor struct {
Id string `json:"id"`
Type string `json:"type"`
Role string `json:"role"`
}
The actors or payload maybe empty. The json maybe
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [
{
"id": "1234567",
"type": "XXX",
"role": "111"
},
{
"id": "7654321",
"type": "YYY",
"role": "222"
}
],
"payload": ""
}
or
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [],
"payload": {
"name": "XXXX",
"number": "1234567"
}
}
If i follow the struct A design and try to marshal json with payload empty, i have to init as below
a := A{
Id: "78a07cea-be2b-499c-b82b-e4f510260484",
Version: "1.0.0",
Actors: []actor{
actor{
Id: "1234567",
Type: "XXX",
Role: "111",
},
actor{
Id: "7654321",
Type: "YYY",
Role: "222",
},
},
Payload: payload{},
}
Which will result in below json with one empty payload struct
{
"id": "78a07cea-be2b-499c-b82b-e4f510260484",
"version": "1.0.0",
"actors": [
{
"id": "1234567",
"type": "XXX",
"role": "111"
},
{
"id": "7654321",
"type": "YYY",
"role": "222"
}
],
"payload": {
"name":"",
"number":""
}
}
Is there any way i can generate
"payload": ""
instead of blank payload struct? Or is there any other struct design for this kind of json format? BTW i cannot pass nil to Payload struct.
The json.Marshaler interface can be implemented to customize JSON encoding, and the json.Unmarshaler interface for decoding (left as an exercise for the reader):
package main
import (
"encoding/json"
"fmt"
)
type A struct {
Payload payload
}
type payload struct {
Name string `json:"name"`
Number string `json:"number"`
}
func (p payload) MarshalJSON() ([]byte, error) {
if p.Name == "" && p.Number == "" {
return []byte(`""`), nil
}
type _payload payload // prevent recursion
return json.Marshal(_payload(p))
}
func main() {
var a A
b, _ := json.MarshalIndent(a, "", " ")
fmt.Println(string(b))
a.Payload.Name = "foo"
b, _ = json.MarshalIndent(a, "", " ")
fmt.Println(string(b))
}
// Output:
// {
// "Payload": ""
// }
// {
// "Payload": {
// "name": "foo",
// "number": ""
// }
// }
Try it on the playground: https://play.golang.org/p/9jhSWnKTnTf
The ad-hoc _payload type is required to prevent recursion. If one would write return json.Marshal(p), the json package would call MarshalJSON again, because p is of type payload, and payload implements json.Marshaler.
The _payload type has the same underlying type as payload but does not implement json.Marshaler (see Type definitions for details), so it is encoded using the standard rules of the json package; it produces exactly the same output that encoding a value of type payload would produce if payload didn't implement json.Marshaler.
Check if using omitempty with json struct tag helps. I think it will result in "payload": {} instead of "payload": ""
Hi there I'm new in GO and I'm trying to convert a json from the facebook api to struct.
The problem is that the keys of the object are dinamic:
{
"100555213756790": {
"id": "100555213756790",
"about": "Noodle Bar & Restaurant",
"metadata": {
"fields": [
{
"name": "id",
"description": "asdasdasdasd",
"type": "numeric string"
},
//...
,
"101285033290986": {
"id": "101285033290986",
"about": "Smart City Expo World Congress",
"metadata": {
"fields": [
{
"name": "id",
"description": "fgddgdfgdg",
"type": "numeric string"
},
what I have achieved so far is extract the objects by id and turn them into a map:
for _, id := range ids {
fbPages, ok := results[string(id)].(map[string]interface{})
if ok {
for k, v := range fbPages {
fmt.Println(k)
fmt.Println(v)
}
}
}
//json to Page struct?
type Page struct {
ID string `json:"id"`
About string `json:"about"`
}
type Metadata struct {
Fields []Field `json:"fields"`
Type string `json:"type"`
Connections map[string]string `json:"connections"`
}
type Field struct {
Name string `json:"name"`
Description string `json:"description"`
Type *string `json:"type,omitempty"`
}
My question is:
how can I convert that map to struct? or is there any easy way to do what I'm trying to do?
Thank you
Converting map to struct:
import "github.com/mitchellh/mapstructure"
mapstructure.Decode(myMap, &myStruct)
example
But I would do this:
type Page struct {
ID string `json:"id"`
About string `json:"about"`
//other fields and nested structs like your metadata struct
}
type fbPages map[string]Page
So, my use case consists of parsing varying JSON schemas into new struct types, which will be further used with an ORM to fetch data from a SQL database. Being compiled in nature, I believe there will not be an out-of-the-box solution in go, but is there any hack available to do this, without creating a separate go process. I tried with reflection, but could not find a satisfactory approach.
Currently, I am using a-h generate library which does generate the structs, but I am stuck at how to load these new struct types in go runtime.
EDIT
Example JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Address",
"id": "Address",
"type": "object",
"description": "address",
"properties": {
"houseName": {
"type": "string",
"description": "House Name",
"maxLength": 30
},
"houseNumber": {
"type": "string",
"description": "House Number",
"maxLength": 4
},
"flatNumber": {
"type": "string",
"description": "Flat",
"maxLength": 15
},
"street": {
"type": "string",
"description": "Address 1",
"maxLength": 40
},
"district": {
"type": "string",
"description": "Address 2",
"maxLength": 30
},
"town": {
"type": "string",
"description": "City",
"maxLength": 20
},
"county": {
"type": "string",
"description": "County",
"maxLength": 20
},
"postcode": {
"type": "string",
"description": "Postcode",
"maxLength": 8
}
}
}
Now, in the above-mentioned library, there is a command line tool, which generates the text for struct type for above json as below:
// Code generated by schema-generate. DO NOT EDIT.
package main
// Address address
type Address struct {
County string `json:"county,omitempty"`
District string `json:"district,omitempty"`
FlatNumber string `json:"flatNumber,omitempty"`
HouseName string `json:"houseName,omitempty"`
HouseNumber string `json:"houseNumber,omitempty"`
Postcode string `json:"postcode,omitempty"`
Street string `json:"street,omitempty"`
Town string `json:"town,omitempty"`
}
Now, the issue is that how to use this struct type without re-compilation in the program. There is a hack, where I can start a new go process, but that doesn't seem a good way to do it. One other way is to write my own parser for unmarshalling JSON schema, something like:
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case float64:
fmt.Println(k, "is float64", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
Can someone please suggest some pointers to look for. Thanks.
So it looks like you're trying to implement your own json marshalling. That's no biggie: the standard json package already supports that. Just have your type implement the MarshalJSON and UnmarshalJSON functions (cf first example on the docs). Assuming some fields will be shared (eg schema, id, type), you can create a unified type like this:
// poor naming, but we need this level of wrapping here
type Data struct {
Metadata
}
type Metadata struct {
Schema string `json:"$schema"`
Type string `json:"type"`
Description string `json:"description"`
Id string `json:"id"`
Properties json.RawMessage `json:"properties"`
Address *Address `json:"-"`
// other types go here, too
}
Now all properties will be unmarshalled into a json.RawMessage field (essentially this is a []byte field). What you can do in your custom unmarshall function now is something like this:
func (d *Data) UnmarshalJSON(b []byte) error {
meta := Metadata{}
// unmarshall common fields
if err := json.Unmarshal(b, &meta); err != nil {
return err
}
// Assuming the Type field contains the value that allows you to determine what data you're actually unmarshalling
switch meta.Type {
case "address":
meta.Address = &Address{} // initialise field
if err := json.Unmarshal([]byte(meta.Properties), meta.Address); err != nil {
return err
}
case "name":
meta.Name = &Name{}
if err := json.Unmarshal([]byte(meta.Properties), meta.Name); err != nil {
return err
}
default:
return errors.New("unknown message type")
}
// all done
d.Metadata = meta // assign to embedded
// optionally: clean up the Properties field, as it contains raw JSON, and is exported
d.Metadata.Properties = json.RawMessage{}
return nil
}
You can do pretty much the same thing for marshalling. First work out what type you're actually working with, then marshal that object into the properties field, and then marhsal the entire structure
func (d Data) MarshalJSON() ([]byte, error) {
var (
prop []byte
err error
)
switch {
case d.Metadata.Address != nil:
prop, err = json.Marshal(d.Address)
case d.Metadata.Name != nil:
prop, err = json.Marshal(d.Name) // will only work if field isn't masked, better to be explicit
default:
err = errors.New("No properties to marshal") // handle in whatever way is best
}
if err != nil {
return nil, err
}
d.Metadata.Properties = json.RawMessage(prop)
return json.Marshal(d.Metadata) // marshal the unified type here
}
Following are my 2 structs
type Attempt struct {
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
LastUpdated string `json:"lastUpdated"`
Duration uint32 `json:"duration"`
SparkUser string `json:"sparkUser"`
IsCompleted bool `json:"completed"`
LastUpdatedEpoch int64 `json:"lastUpdatedEpoch"`
StartTimeEpoch int64 `json:"startTimeEpoch"`
EndTimeEpoch int64 `json:"EndTimeEpoch"`
}
type Apps struct {
Id string `json:"id"`
Name string `json:"name"`
Attempts []Attempt `json:"attempts"`
}
The following test parses a json string into this apps := &[]Apps{}. When accessing the members of apps, I am getting the following error
invalid operation: apps[0] (type *[]Apps does not support indexing)
The test
func TestUnmarshalApps(t *testing.T) {
appsJson := `[
{
"id": "app-20161229224238-0001",
"name": "Spark shell",
"attempts": [
{
"startTime": "2016-12-30T03:42:26.828GMT",
"endTime": "2016-12-30T03:50:05.696GMT",
"lastUpdated": "2016-12-30T03:50:05.719GMT",
"duration": 458868,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069805696,
"lastUpdatedEpoch": 1483069805719,
"startTimeEpoch": 1483069346828
},
{
"startTime": "2016-12-30T03:42:26.828GMT",
"endTime": "2016-12-30T03:50:05.696GMT",
"lastUpdated": "2016-12-30T03:50:05.719GMT",
"duration": 458868,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069805696,
"lastUpdatedEpoch": 1483069805719,
"startTimeEpoch": 1483069346828
}
]
},
{
"id": "app-20161229222707-0000",
"name": "Spark shell",
"attempts": [
{
"startTime": "2016-12-30T03:26:50.679GMT",
"endTime": "2016-12-30T03:38:35.882GMT",
"lastUpdated": "2016-12-30T03:38:36.013GMT",
"duration": 705203,
"sparkUser": "esha",
"completed": true,
"endTimeEpoch": 1483069115882,
"lastUpdatedEpoch": 1483069116013,
"startTimeEpoch": 1483068410679
}
]
}
]`
apps := &[]Apps{}
err := json.Unmarshal([]byte(appsJson), apps)
if err != nil {
t.Fatal(err)
}
if len(*apps) != 2 {
t.Fail()
}
if len(apps[0].Attempts) != 2 {
t.Fail()
}
}
How to access the fields Attempts, Id etc.?
apps := &[]Apps{}
apps has type *[]Apps (pointer to slice of Apps objects).
Are you sure you didn't mean to use the type []*Apps (slice of pointers to Apps objects)?
Assuming *[]Apps really is the type you intended, you'd need to use (*apps)[i] to access every element of apps. That type is also the reason why you also need to use len(*apps) instead of len(apps) (and *apps for pretty much everything actually).
If given the string, from a MediaWiki API request:
str = ` {
"query": {
"pages": {
"66984": {
"pageid": 66984,
"ns": 0,
"title": "Main Page",
"touched": "2012-11-23T06:44:22Z",
"lastrevid": 1347044,
"counter": "",
"length": 28,
"redirect": "",
"starttimestamp": "2012-12-15T05:21:21Z",
"edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
}
}
}
}`
What can be done to get the edittoken, using Go's json package (keep in mind the 66984 number will continually change)?
When you have a changing key like this the best way to deal with it is with a map. In the example below I've used structs up until the point we reach a changing key. Then I switched to a map format after that. I linked up a working example as well.
http://play.golang.org/p/ny0kyafgYO
package main
import (
"fmt"
"encoding/json"
)
type query struct {
Query struct {
Pages map[string]interface{}
}
}
func main() {
str := `{"query":{"pages":{"66984":{"pageid":66984,"ns":0,"title":"Main Page","touched":"2012-11-23T06:44:22Z","lastrevid":1347044,"counter":"","length":28,"redirect":"","starttimestamp":"2012-12-15T05:21:21Z","edittoken":"bd7d4a61cc4ce6489e68c21259e6e416+\\"}}}}`
q := query{}
err := json.Unmarshal([]byte(str), &q)
if err!=nil {
panic(err)
}
for _, p := range q.Query.Pages {
fmt.Printf("edittoken = %s\n", p.(map[string]interface{})["edittoken"].(string))
}
}
Note that if you use the &indexpageids=true parameter in the API request URL, the result will contain a "pageids" array, like so:
str = ` {
"query": {
"pageids": [
"66984"
],
"pages": {
"66984": {
"pageid": 66984,
"ns": 0,
"title": "Main Page",
"touched": "2012-11-23T06:44:22Z",
"lastrevid": 1347044,
"counter": "",
"length": 28,
"redirect": "",
"starttimestamp": "2012-12-15T05:21:21Z",
"edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
}
}
}
}`
so you can use pageids[0] to access the continually changing number, which will likely make things easier.