Home > Backend Development > Golang > How to Read JSON Files as JSON Objects in Go?

How to Read JSON Files as JSON Objects in Go?

Barbara Streisand
Release: 2024-11-11 10:19:02
Original
824 people have browsed it

How to Read JSON Files as JSON Objects in Go?

Reading JSON Files as JSON Objects in Go

To read a JSON file as a JSON object in Go, it's crucial to understand the concept of pointers and type assertion.

Reading the JSON File

plan, err := ioutil.ReadFile(filename)
if err != nil {
    log.Fatal(err)
}
Copy after login

Unmarshaling the Data

To store the JSON object, you'll need a pointer to a variable, as specified in the Go documentation:

var data interface{}
if err := json.Unmarshal(plan, &data); err != nil {
    log.Fatal(err)
}
Copy after login

This stores the JSON object in the memory location pointed to by data.

Accessing the JSON Object

Since data is an interface, you must use type assertion to access its underlying values:

switch data := data.(type) {
case map[string]interface{}:
    // Loop through the map as a JSON object
    for key, value := range data {
        fmt.Println(key, value)
    }
case []interface{}:
    // Loop through the slice as a JSON array
    for _, value := range data {
        fmt.Println(value)
    }
default:
    // Handle other types as needed
}
Copy after login

Marshaling for Debugging

If you need to view the JSON object as a string for debugging purposes, you can use:

jsonString, err := json.Marshal(data)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(jsonString))
Copy after login

Note:

  • Ensure that the JSON file is correctly formatted and contains valid JSON data.
  • Use a specific data structure to populate your JSON when possible, rather than an empty interface.

The above is the detailed content of How to Read JSON Files as JSON Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template