-3

I am using golang to parse a json string:

str:="{...}"
var f interface{}
json.Unmarshal([]byte(str), f)

fmt.Println(f)

While I got nil in the console.

When I change the code to :

json.Unmarshal([]byte(str), &f)

It will print the json string.

What's going on?

3
  • Sorry, I didn't find that. Commented Jan 28, 2018 at 4:53
  • Don't ignore errors. Commented Jan 28, 2018 at 11:53
  • I think research doesn't help always. Sometimes you can't find answer if you don't know correct question. I also think who has 10.6k reputation, didn't come here for upvote. Commented Jan 28, 2018 at 11:58

1 Answer 1

4

Two things are happening:

  1. You didn't read the documentation.
  2. You didn't check json.Unmarshal's return value to check for errors.

From the fine manual:

func Unmarshal(data []byte, v interface{}) error

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Unmarshal takes an interface{} because it can unmarshal into all sorts of things (slices, maps, structs, ...) as noted in the documentation.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.