解析未知的 JSON 文件并对其进行迭代。

huangapple go评论128阅读模式
英文:

Parsing unknown JSON from file and iterate into it

问题

我有这样的JSON数据:

{
    "store_name": "巴里的农贸市场",
    "foods": {
        "apple": "5.91",
        "peach": "1.84",
        "carrot": "6.44",
        "beans": "3.05",
        "orange": "5.75",
        "cucumber": "6.42"
    },
    "store_location": "Elm Tree Hill街和158th街的拐角处"
}

我想将其解析为一个未知的JSON,使用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("错误:%v", err)
        os.Exit(1)
    }

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

}

考虑到v不会转换为字符串,并且我想遍历所有在"foods"中的值,你能帮我吗?我觉得我漏掉了什么...

英文:

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...

答案1

得分: 5

如果你阅读了json.Unmarshal的文档,你可以看到它将使用哪些类型,并根据此来编写代码;或者使用fmt.Printf("%T",v)来查看运行时的类型。

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

工作示例:https://play.golang.org/p/nczV5qA41h

英文:

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

得分: 1

你可以创建一个包含map[string]string的结构体,并对其进行迭代。以下是示例代码:

type Store struct {
    Name     string            `json:"store_name"`
    Foods    map[string]string `json:"foods"`
    Location string            `json:"store_location"`
}

func main() {
    var store Store
    data := []byte(jsonData)
    err := json.Unmarshal(data, &store)
    if err != nil {
       panic(err)
    }
    for k, v := range store.Foods {
       fmt.Println(k + v)
    }
}

这段代码使用了Store结构体来存储数据,并使用json.Unmarshal函数将JSON数据解析到store变量中。然后,通过range循环遍历store.Foods中的键值对,并打印它们。

英文:

You could just make a structure which contains a map[string]string and iterate over that. https://play.golang.org/p/IVlrTTcrVB

type Store struct {
    Name     string            `json:"store_name"`
    Foods    map[string]string `json:"foods"`
    Location string            `json:"store_location"`
}

func main() {
    var store Store
    data := []byte(jsonData)
    err := json.Unmarshal(data, &store)
    if err != nil {
       panic(err)
    }
    for k, v := range store.Foods {
       fmt.Println(k + string(v))
    }
}

答案3

得分: 1

fastjson 可用于解析未知的 JSON 并对其进行迭代:

var p fastjson.Parser
v, err := p.Parse(input)
if err != nil {
    log.Fatal(err)
}

// Visit 将为 v.foods 中的每个项调用回调函数。
v.GetObject("foods").Visit(func(foodName []byte, foodValue *fastjson.Value) {
    fmt.Printf("%s = %s\n", foodName, foodValue)
})
英文:

fastjson may be used for parsing unknown JSON and iterating into it:

var p fastjson.Parser
v, err := p.Parse(input)
if err != nil {
    log.Fatal(err)
}

// Visit will call the callback for each item in v.foods.
v.GetObject("foods").Visit(func(foodName []byte, foodValue *fastjson.Value) {
    fmt.Printf("%s = %s\n", foodName, foodValue)
})

huangapple
  • 本文由 发表于 2017年9月2日 03:45:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/46007073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定