0

I am trying to parse a JSON of the type

"{\"ids\":[\"a\",\"b\"]}"

Here is my code:

package main

import "fmt"
import "encoding/json"
import "strings"

type Idlist struct {
    id []string `json:"ids"`
}
func main() {
    var val []byte = []byte(`"{\"ids\":[\"a\",\"b\"]}"`)
    jsonBody, _ := strconv.Unquote(string(val))

    var holder Idlist
    if err := json.NewDecoder(strings.NewReader(jsonBody)).Decode(&holder); err!= nil{
        fmt.Print(err)
    }
    fmt.Print(holder)
    fmt.Print(holder.id)
}

However, I keep getting output

{[]}[]

I cannot get the data in the structure. Where am I going wrong? Here is the playground link: https://play.golang.org/p/82BaUlfrua

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Puja Roy
  • 61
  • 6
  • 1
    And the next one. Did you take the Go Tour? Did you read the whole documentation of encoding/json? – Volker Nov 25 '15 at 10:35
  • Possible duplicate of [JSON and dealing with unexported fields](https://stackoverflow.com/questions/11126793/json-and-dealing-with-unexported-fields) – Jonathan Hall May 31 '18 at 06:39

2 Answers2

1

Your struct has to look like :

type Idlist struct {
    Id []string `json:"ids"`
}

Golang assumes that the fields starting with capital case are public. Hence, your fields are not visible to json decoder. For more details please look into this post : Why Golang cannot generate json from struct with front lowercase character?

Community
  • 1
  • 1
novieq
  • 88
  • 1
  • 2
  • 14
0

This is example how you can resolve your problem: http://play.golang.org/p/id4f4r9tEr

You might need to use strconv.Unquote on your string.

And this is probably duplicate: How to unmarshal an escaped JSON string in Go?

Resolved: https://play.golang.org/p/hAShmfDUA_

type Idlist struct {
    Id []string `json:"ids"`
}
Community
  • 1
  • 1
mikicaivosevic
  • 157
  • 1
  • 7
  • The example you quote is a starter example. Not that mine is any harder. I am specifically looking for a case where there is an array in the json. Can you please point out the error in my approach. I have attached a go playground link with the code for your convenience. Thanks for your time in advance. Appreciate it. – Puja Roy Nov 25 '15 at 09:21
  • Updated the question with your tip and with a new go playground link. – Puja Roy Nov 25 '15 at 09:26
  • dude you dont even know anything about golang. Why the hell are you ruining my question ? – Puja Roy Nov 25 '15 at 09:38
  • Thank you for you comment, it's true, I don't know Go lang, but I have resolved you problem. Problem is in your structure, you can't use lowercase. https://play.golang.org/p/hAShmfDUA_ Now it works – mikicaivosevic Nov 25 '15 at 09:50
  • Cool thanks man. You are awesome. Sorry for the harsh words. I spent hours on this silly thing and studied the whole lot of parsing. – Puja Roy Nov 25 '15 at 09:57
  • No problem, I'm glad I was of any help! – mikicaivosevic Nov 25 '15 at 10:08