douzi2749 2017-09-01 19:45
浏览 100
已采纳

从文件解析未知的JSON并迭代到其中

I have JSON like this:

{
    "store_name": "Barry's Farmer's Market",
    "foods": {
        "apple": "5.91",
        "peach": "1.84",
        "carrot": "6.44",
        "beans": "3.05",
        "orange": "5.75",
        "cucumber": "6.42"
    },
    "store_location": "Corner of Elm Tree Hill and 158th Street"
} 

And I want to parse it as an unknown JSON using a map[string]interface{}:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    var parsed map[string]interface{}

    f, err := ioutil.ReadFile("input.txt")
    if err != nil {
        fmt.Printf("Error: %v", err)
        os.Exit(1)
    }

    err = json.Unmarshal(f, &parsed)
    for k, v := range parsed {
        //fmt.Println(parsed["foods"])
        fmt.Println(k + string(v))
    }

}

Considering that "v" doesn't convert to string and that I want to range all the values in "foods", can you help me? I think i'm missing something...

  • 写回答

3条回答 默认 最新

  • doutongfu9484 2017-09-01 19:48
    关注

    If you read the documentation for json.Unmarshal, you can see what types it will use, and base your code on that; or use fmt.Printf("%T",v) to see what type it is at runtime.

    err = json.Unmarshal(f, &parsed)
    for k, v := range parsed["foods"].(map[string]interface{}) {
        fmt.Println(k, v)
    }
    

    Working playground example: https://play.golang.org/p/nczV5qA41h

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮