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

How Do You Read JSON Files as Objects in Go?

Mary-Kate Olsen
Release: 2024-11-15 00:57:02
Original
362 people have browsed it

How Do You Read JSON Files as Objects in Go?

Reading JSON Files as Object in Go

In Go, you can encounter difficulties when attempting to read a JSON file and parse it as a JSON object.

Failed Attempts

Some failed attempts to read JSON files as objects include:

  • Attempt 1:
plan, _ := ioutil.ReadFile(filename) // filename is the JSON file to read
var data interface{}
err := json.Unmarshal(plan, data)
Copy after login

This results in the error "json: Unmarshal(nil)".

  • Attempt 2:
generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct
Copy after login

This produces a string output, but casting it to a string makes it impossible to loop through as a JSON object.

Solution

The key to resolving this issue lies in the value pointed to by json.Unmarshal. It must be a pointer.

plan, _ := ioutil.ReadFile(filename)
var data interface{}
err := json.Unmarshal(plan, &data)
Copy after login

Type Assertion

When using an empty interface in unmarshal, you need to use type assertion to get underlying values as native Go types:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
Copy after login

Best Practice

It's highly recommended to use a concrete structure to populate JSON data using Unmarshal. This provides better clarity and avoids the need for type assertions.

The above is the detailed content of How Do You Read JSON Files as 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