duan0531 2015-02-21 08:47
浏览 408
已采纳

您如何使用go-simplejson遍历json文件

I have a JSON file of the form:

{
  "data": {
    "docs": [
      {"key00": "val00", "key01": "val01"},
      {"key10": "val10", "key11": "val11"}
    ]
  }
}

and I would like to convert it to separate JSON docs:

file0.json

{
  {"key00": "val00", "key01": "val01"}
}

file1.json

{
   {"key10": "val10", "key11": "val11"}
}

I can enumerate over the array contents using:

j, _ := ioutil.ReadFile(path)
dec, _ := simplejson.NewFromReader(bytes.NewReader(j))
for i,v := range dec.Get("data").Get("docs").MustArray() {
  out := simplejson.New()

  /* ??? move dec key/value pairs to out ??? */

  b, _ := out.EncodePretty()
  ioutil.WriteFile(outpath, b, 0777)
}

but I'm not sure how to iterate over the key/value pairs within the array entries. It's a nice, succinct library but there don't appear to be a lot of examples and my golang expertise is currently limited.

Any help would be appreciated.. thanks!

  • 写回答

2条回答 默认 最新

  • duaj39673 2015-02-21 12:30
    关注

    You can use simplejson.Set:

    for _, doc := range dec.Get("data").Get("docs").MustArray() {
        out := simplejson.New()
        // doc is an interface{} holding a map, we have to type assert it.
        for k, v := range doc.(map[string]interface{}) {
            out.Set(k, v)
        }
        b, _ := out.EncodePretty()
        fmt.Printf("%s
    ", b)
    }
    

    However in that instance, simplejson is an overkill and using a struct / stdlib is more efficient.

    For completeness sake, the std lib version:

    type DataLayout struct {
        Data struct {
            Docs []map[string]string `json:"docs"`
        } `json:"data"`
    }
    
    func main() {
        var in DataLayout
        err := json.NewDecoder(strings.NewReader(j)).Decode(&in)
        if err != nil {
            log.Fatal(err)
        }
        for _, doc := range in.Data.Docs {
            b, err := json.MarshalIndent(doc, "", "\t")
            if err != nil {
                log.Fatal(err)
            }
            fmt.Printf("%s
    ", b)
        }
    }
    

    <kbd>play</kbd>

    Notes:

    • Your json example is wrong, "key10", "val10" should be "key10": "val10".
    • When you're in doubt of how a data structure looks and too lazy to read the code, use fmt.Printf("%#v", doc) to see how it looks like.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)