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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)