在Golang中的json.Marshal之前添加密钥

时间:2017-03-21 07:17:49

标签: json go marshalling

我正在创建一个函数来获取对象数组并将其保存到Struct中。然后我想将其转换为JSON。

@foreach($doctor->clinics as $clinic)
    <form method="POST" 
        action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
        id="formremoveclinic{{$clinic->id}}">
        {{csrf_field()}}
        <button class="btn btn-sm btn-danger pull-right">
            <span class="glyphicon glyphicon-remove"></span>
        </button>
    </form>
    <p class="text-muted">Clinic {{$i++}}</p>
    <p class="text-muted">{{$clinic->address}}</p>
    <hr>
    <script>
        $("#formremoveclinic{{$clinic->id}}").submit(function(e){
            $('#loading').show();
            e.preventDefault();
            $.ajax({
                url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
                type: "DELETE",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData:false,
                success: function(data){
                    $('#loading').hide();
                },
                error: function(data){
                    var errors = data.responseJSON;
                    console.log(errors);
                    $('#loading').hide();

                }           
            });
        });
    </script>
@endforeach

这是结构

func GetCountry(msg string) []byte {
    var countries []*countryModel.Country

    countries = countryModel.GetAllCountry()

    jsResult, err := json.Marshal(countries)

    if err != nil {
        logger.Error(err, "Failed on GetCountry")
    }

    return jsResult
}

使用该功能,我得到了这些结果

type Country struct {
    Id           int    `json:"id"`
    CountryCode string `json:"country_code"`
    CountryName string `json:"country_name"`
    PhoneCode   string `json:"phone_code"`
    Icon         string `json:"icon"`
}

如何为该JSON结果添加名为“countries”的键?这些是我所期待的

[
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  },
  {
    "id": 2,
    "country_code": "MY",
    "country_name": "Malaysia",
    "phone_code": "+60",
    "icon": "no-data"
  }
]

请帮忙

1 个答案:

答案 0 :(得分:1)

你可以创建一个包含一个国家结构数组的包装器结构,在states数组声明之后使用json: "countries",然后在包装器上调用json.Marshal。

它看起来像什么:

type CountryWrapper struct {
  Countries []*countryModel.Country `json: "countries"`
} 

然后,在您的方法中,实例化为CountryWrapper{ Countries: countries },并在此对象上调用json.Marshal。

相关问题