Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse the following JSON structure in Go

Tags:

json

parsing

go

In Go, how can I parse the following JSON? I know to use struct to parse, but the keys are different for each entry, also they are not fixed, they can be more or less.

{
  "consul": [],
  "docker": [],
  "etcd": ["etcd"],
  "kubernetes": ["secure"],
  "mantl-api": [],
  "marathon": ["marathon"],
  "mesos": ["agent", "follower", "leader", "master"],
  "mesos-consul": [],
  "zookeeper": ["mantl"]
}

Thanks for help!

like image 879
jisan Avatar asked Jul 13 '16 00:07

jisan


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 you parse JSON?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Can you write JSON file using Go language?

Reading and Writing JSON Files in GoIt is actually pretty simple to read and write data to and from JSON files using the Go standard library. For writing struct types into a JSON file we have used the WriteFile function from the io/ioutil package. The data content is marshalled/encoded into JSON format.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.


1 Answers

If json values are always an []string you can convert it with

json.Unmarshal(value, &map[string][]string)

But if not, best way to do this is Unmarshal JSON in a map[string]interface{} and check each field type you want to.

like image 142
Tarsis Azevedo Avatar answered Oct 28 '22 15:10

Tarsis Azevedo