Home  >  Article  >  Backend Development  >  How to deserialize json with anonymous array in Golang?

How to deserialize json with anonymous array in Golang?

WBOY
WBOYforward
2024-02-14 11:24:21846browse

如何在 Golang 中用匿名数组反序列化 json?

In Golang, how to use anonymous arrays to deserialize json data? This is a problem that many developers often encounter. Anonymous arrays can easily handle some simple data structures without defining specific structures. By using Golang's built-in json package, we can easily implement this functionality. Below, PHP editor Xinyi will introduce you in detail how to use anonymous arrays to deserialize json data in Golang. Let’s take a look!

Question content

I receive this json from an external server:

[["010117", "070117", "080117"], ["080117", "140117", "150117"], ["150117", "210117", "220117"]]

I need to parse it

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "os"
    "runtime"
)

type Range struct {
    From string
    To   string
    Do   string
}

type AllRanges struct {
    Ranges []Range
}

func main() {
    var ranges AllRanges
    j, err := os.ReadFile(file)

    if err != nil {
        panic("Can't read json file")
    }

    if json.Unmarshal(j, &v) != nil {
        panic("Error reading the json")
    }
}

When I execute, a panic is thrown indicating an error while reading json

Thanks in advance!

Solution

  1. This is not a failing code. The code you posted will not compile because it attempts to unmarshal into an undeclared variable v.

  2. Assuming v should be ranges, the problem is very simple....

ranges is of type allranges, which is a structure with named members, and ranges is an array of structures, which also has named members.

So when trying to unmarshal json into this structure, the unmarshaler will expect to find:

{
   "ranges": [
        { 
           "from": "..",
           "to": ..,
           "do": ".."
        },
        { etc }
   ]
}

To unmarshal data from an anonymous array of string arrays, you need to declare ranges as an array of string arrays:

    var ranges [][]string

    ...

    if json.Unmarshal(j, &ranges) != nil {
        panic("Error reading the json")
    }

Once unmarshalled into this array of arrays, you need to write code to convert it into the desired structured value.

This playground demonstrates how to successfully unmarshal sample data into [][]string. Transformation is left as an exercise.

The above is the detailed content of How to deserialize json with anonymous array in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete