0

I am receiving this json from an external server:

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

and 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 it is thrown indicating an error reading the json

Thanks in advance !

1
  • 1
    You either have to unmarshal the JSON into compatible Go types (e.g., strings to strings, numbers to ints or floats, arrays into slices, objects into maps or structs), or you have to implement the unmarshaler interface. At this point there should be over a thousand examples, just here on SO, of how to do that. Commented Feb 11, 2023 at 18:06

1 Answer 1

2
  1. This isn't the code that is failing. The code you have posted won't compile as it attempts to unmarshal into an undeclared variable, v.

  2. Assuming that v is supposed to be ranges, the problem is very simple....

ranges is of type AllRanges which is a struct having a named member Ranges which is an array of structs, also having named members.

Therefore, when attempting to unmarshal json into this struct, the unmarshaller will expect to find:

{
   "Ranges": [
        { 
           "From": "..",
           "To": ..,
           "Do": ".."
        },
        { etc }
   ]
}

To unmarshal your data, consisting of an anonymous array of arrays of string, you need instead to declare ranges as an array of array of strings:

    var ranges [][]string

    ...

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

Once you have unmarshalled into this array of arrays you will then need to write code to transform it into the desired structured values.

This playground demonstrates successfully unmarshalling your sample data into a [][]string. Transformation is left as an exercise.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.