简体   繁体   中英

Is there any way to parse json file dynamically GO

I have a json file, but I don't know what the content and format of this json file is. It can change instantly.

So I cannot create a struct and parse it according to this struct.

Is there a way to dynamically parse this json file and access the values in this json?

I couldn't find anything, if you have any help I'm open to it.

Yes, you can parse a JSON file dynamically in Go by using the built-in encoding/json package and an interface type. Here's an example:

package main

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

func main() {
    // Read the JSON file into memory
    file, err := ioutil.ReadFile("file.json")
    if err != nil {
        fmt.Println(err)
        return
    }

    // Unmarshal the JSON into a dynamic interface
    var data interface{}
    err = json.Unmarshal(file, &data)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Access the values using type assertions
    m := data.(map[string]interface{})
    for k, v := range m {
        fmt.Println(k, v)
    }
}

In this example, the json.Unmarshal function is used to parse the JSON file into an interface{} type, which is a dynamic type in Go that can hold any value. The values in the JSON can then be accessed using type assertions to convert the dynamic type to a more specific type, such as map[string]interface{}.

Is this what you mean?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM