Asked  7 Months ago    Answers:  5   Viewed   37 times
type TestObject struct {
    kind string `json:"kind"`
    id   string `json:"id, omitempty"`
    name  string `json:"name"`
    email string `json:"email"`

func TestCreateSingleItemResponse(t *testing.T) {
    testObject := new(TestObject)
    testObject.kind = "TestObject" = "f73h5jf8" = "Yuri Gagarin" = ""


    b, err := json.Marshal(testObject)

    if err != nil {


Here is the output:

[ `go test"^TestCreateSingleItemResponse$"` | done: 2.195666095s ]
    {TestObject f73h5jf8 Yuri Gagarin}

Why is the JSON essentially empty?



You need to export the fields in TestObject by capitalizing the first letter in the field name. Change kind to Kind and so on.

type TestObject struct {
 Kind string `json:"kind"`
 Id   string `json:"id,omitempty"`
 Name  string `json:"name"`
 Email string `json:"email"`

The encoding/json package and similar packages ignore unexported fields.

The `json:"..."` strings that follow the field declarations are struct tags. The tags in this struct set the names of the struct's fields when marshaling to and from JSON.

Ru it on the playground.

Tuesday, June 1, 2021
answered 7 Months ago

In Yii2 you don't use model() method. Because, Yii2 and Yii1 is different(see more In Yii1 to provide data like that:


In Yii2 to provide data like that:

Post::find()->where(['type' => $id])->all(); 

See more

Delete model in your model:

public static function model($className=__CLASS__)
    return parent::model($className);

And change loadItems method to:

private static function loadItems($type)

    foreach ($models as $model)
Saturday, May 29, 2021
answered 7 Months ago

Looks like you are attempting to run multiple statements, possibly through a mysql_query() or mysqli->query() which only support single statements. Instead you need to execute this with mysqli->multi_query() or mysql_multi_query().

Saturday, May 29, 2021
answered 7 Months ago

Working playground link:

The gist of it is this; by using the reflect package we loop over the fields of the struct we wish to serialize and map them to a map[string]interface{} we can now retain the flat structure of the original struct without introducing new fields.

Caveat emptor, there should probably be several checks against some of the assumptions made in this code. For instance it assumes that MarshalHateoas always receives pointers to values.

package main

import (

type User struct {
    Id   int    `json:"id"`
    Name string `json:"name"`

type Session struct {
    Id     int `json:"id"`
    UserId int `json:"userId"`

func MarshalHateoas(subject interface{}) ([]byte, error) {
    links := make(map[string]string)
    out := make(map[string]interface{})
    subjectValue := reflect.Indirect(reflect.ValueOf(subject))
    subjectType := subjectValue.Type()
    for i := 0; i < subjectType.NumField(); i++ {
        field := subjectType.Field(i)
        name := subjectType.Field(i).Name
        out[field.Tag.Get("json")] = subjectValue.FieldByName(name).Interface()
    switch s := subject.(type) {
    case *User:
        links["self"] = fmt.Sprintf("http://user/%d", s.Id)
    case *Session:
        links["self"] = fmt.Sprintf("http://session/%d", s.Id)
    out["_links"] = links
    return json.MarshalIndent(out, "", "    ")
func main() {
    u := &User{123, "James Dean"}
    s := &Session{456, 123}
    json, err := MarshalHateoas(u)
    if err != nil {
    } else {
        fmt.Println("User JSON:")
    json, err = MarshalHateoas(s)
    if err != nil {
    } else {
        fmt.Println("Session JSON:")
Thursday, August 12, 2021
answered 4 Months ago

You can implement a Marshaler like this (or this )

package main

import "fmt"
import "encoding/json"

type Deck struct {
    Cards []int

func (d Deck) Value() int {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    return value
func (d Deck) Size() int {
    return len(d.Cards)

func (d Deck) MarshalJSON() ([]byte, error) {
    value := 0
    for _, v := range d.Cards {
        value = value + v

    return json.Marshal(struct {
        Cards []int `json:"cards"`
        Value int   `json:"value"`
        Size  int   `json:"size"`
        Cards: d.Cards,
        Value: d.Value(),
        Size:  d.Size(),

func main() {
    deck := Deck{
        Cards: []int{1, 2, 3},

    b, r := json.Marshal(deck)
Monday, November 1, 2021
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :