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

2
  • 1
    And the next one. Did you take the Go Tour? Did you read the whole documentation of encoding/json? Commented Nov 25, 2015 at 10:35
  • Possible duplicate of JSON and dealing with unexported fields Commented May 31, 2018 at 6:39

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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"` } 

6 Comments

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.
Updated the question with your tip and with a new go playground link.
dude you dont even know anything about golang. Why the hell are you ruining my question ?
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. play.golang.org/p/hAShmfDUA_ Now it works
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.