5

I have a really simple JSON file, something like this, but with thousands of strings:

{"fruits":["apple","banana","cherry","date"]}

and I want to load the fruits into a

map[string]interface{}

What is the best method? Is there a way where I don't need to iterate over each element and insert into the map using a loop?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
recis
  • 215
  • 1
  • 2
  • 10
  • 2
    Try to implement some code, and ask specific question regarding the code. The community is in a better position to solve your problems in that aspect. – Ketan Dubey Jul 14 '17 at 10:00
  • You could see the link bellow, it helped me: https://stackoverflow.com/questions/443499/convert-json-to-map – Víctor López Jul 14 '17 at 10:00
  • Thanks Victor, I'm looking for something similar in Go. Using the "usual" unmarshal example I can get a map, but it will contain the whole fruits part in one, and I still need to iterate over it when adding them to a new map - if I understood the go examples well. – recis Jul 14 '17 at 10:13
  • 1
    Hi you can create a list of strings: https://play.golang.org/p/qDc3kn1JjE – Raimondas Kazlauskas Jul 14 '17 at 10:26
  • Thanks! Do I need to define a struct for this if it only contains a slice? – recis Jul 14 '17 at 10:35
  • This is one of the most asked Go questions on SE. Try searching, or reading the docs. When you're stuck, show us your code to ask for help. – Flimzy Jul 14 '17 at 11:18

1 Answers1

9

here is example how you can Unmarshal to string list without any struct.

package main

import "fmt"
import "encoding/json"

func main() {
    src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
    var m map[string][]string
    err := json.Unmarshal(src_json, &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v", m["fruits"][0]) //apple
 }

Or instead of String list you can use map[string][]interface{}