How to parse JSON array in Go

91,791

Solution 1

The return value of Unmarshal is an error, and this is what you are printing out:

// Return value type of Unmarshal is error.
err := json.Unmarshal([]byte(dataJson), &arr)

You can get rid of the JsonType as well and just use a slice:

package main

import (
    "encoding/json"
    "log"
)

func main() {
    dataJson := `["1","2","3"]`
    var arr []string
    _ = json.Unmarshal([]byte(dataJson), &arr)
    log.Printf("Unmarshaled: %v", arr)
}

// prints out:
// 2009/11/10 23:00:00 Unmarshaled: [1 2 3]

Code on play: https://play.golang.org/p/GNWlylavam

Background: Passing in a pointer allows Unmarshal to reduce (or get entirely rid of) memory allocations. Also, in a processing context, the caller may reuse the same value to repeatedly - saving allocations as well.

Solution 2

Note: This answer was written before the question was edited. In the original question &arr was passed to json.Unmarshal():

unmarshaled := json.Unmarshal([]byte(dataJson), &arr)

You pass the address of arr to json.Unmarshal() to unmarshal a JSON array, but arr is not an array (or slice), it is a struct value.

Arrays can be unmarshaled into Go arrays or slices. So pass arr.Array:

dataJson := `["1","2","3"]`
arr := JsonType{}
err := json.Unmarshal([]byte(dataJson), &arr.Array)
log.Printf("Unmarshaled: %v, error: %v", arr.Array, err)

Output (try it on the Go Playground):

2009/11/10 23:00:00 Unmarshaled: [1 2 3], error: <nil>

Of course you don't even need the JsonType wrapper, just use a simple []string slice:

dataJson := `["1","2","3"]`
var s []string
err := json.Unmarshal([]byte(dataJson), &s)
Share:
91,791
kingSlayer
Author by

kingSlayer

Updated on July 13, 2022

Comments

  • kingSlayer
    kingSlayer almost 2 years

    How to parse a string (which is an array) in Go using json package?

    type JsonType struct{
        Array []string
    }
    
    func main(){
        dataJson = `["1","2","3"]`
        arr := JsonType{}
        unmarshaled := json.Unmarshal([]byte(dataJson), &arr.Array)
        log.Printf("Unmarshaled: %v", unmarshaled)
    }
    
  • kingSlayer
    kingSlayer over 7 years
    I forgot that I pass the address, and thought it returned the parsed array, so that why the result was <nil> because it was the value of the error, shame on me.
  • icza
    icza over 7 years
    @kingSlayer You have to pass the address of the variable so the json package can unmarshal right into your variable. The result doesn't need to be returned, but the optional error have to be.
  • kingSlayer
    kingSlayer over 7 years
    So my problem was that I printed out the value of error and not the pointed value of the arr.Array, that was the confusion for me, Thanks.
  • icza
    icza over 7 years
    @kingSlayer Yeah, you edited your question, but in your original question you passed arr which results in an error.