Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON array in Go

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) } 
like image 822
kingSlayer Avatar asked Aug 10 '16 08:08

kingSlayer


People also ask

How do I decode JSON in Golang?

Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct.

How do I read JSON data in Golang?

json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.

What is Unmarshal Golang?

Golang Unmarshal Unmarshal is the contrary of marshal. It allows you to convert byte data into the original data structure. In go, unmarshaling is handled by the json. Unmarshal() method.

How do you declare a JSON object in Golang?

Declare types that match the structure of the JSON document. Initialize values using those types and encode to JSON. The JSON field tags ( json:"Hostname" ) are not needed in this example because the JSON object keys are valid exported identifiers. I include the tags here because they are often needed.


2 Answers

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.

like image 168
miku Avatar answered Sep 18 '22 01:09

miku


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) 
like image 23
icza Avatar answered Sep 18 '22 01:09

icza