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>

    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏