dongqianzong4275 2014-12-17 23:53
浏览 19

Go中的嵌套数据结构-等同于Python

I can create this data structure in Python really easily:

data = {'Locations': [],
 'Dates': [],
 'Properties': [{'key': 'data1', 'value': 'data2'}],
 'Category': 'all'}

Which can then be marshalled to JSON in Python just as easily. e.g.

print json.dumps(data)

{"Category": "all", "Dates": [], "Locations": [], "Properties": [{"value": "data2", "key": "data1"}]}

However, I'm tearing my hair out trying to create the same structure then convert it to JSON in Go. Go looks to be very promising and just what I need for creating cross platform applications, but boy this stuff seems to be frustratingly difficult.

This is what I've tried, however I cant get the structure to include the square brackets that should surround the properties element.

import (
"fmt"
"encoding/json"
)

func main() {

data := map[string]interface{}{"Offset": "0", "Properties": map[string]string{"value": "data2", "key": "data1"}, "Category": "all", "Locations": []string{}, "Dates": []string{} }
    data_json, _ := json.Marshal(data)
fmt.Println(string(data_json))
}

Which outputs:

{"Category":"all","Dates":[],"Locations":[],"Offset":"0","Properties":{"key":"data1","value":"data2"}}

Heres a demo: http://play.golang.org/p/49Kytg6v_C

  • 写回答

2条回答 默认 最新

  • douwei1128 2014-12-18 00:03
    关注

    You just need to create a slice of map[string]string:

    data := map[string]interface{}{
        "Offset":     "0",
        "Properties": []map[string]string{{"value": "data2", "key": "data1"}},
        "Category":   "all",
        "Locations":  []string{},
        "Dates":      []string{},
    }
    

    <kbd>playground</kbd>

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效