Tuesday, March 14, 2023
HomeGolangThe way to know which line of json is failing to unmarshal?...

The way to know which line of json is failing to unmarshal? – Getting Assist

I’m engaged on an app that makes use of go to parse a json file for settings. I get the error proven beneath, but it surely’s not telling me what line within the json file is inflicting the difficulty. How do I see this?

panic: json: can not unmarshal string into Go worth of kind map[string]*json.RawMessage

You possibly can verify your Go code to see the place you’ve got a subject of kind map[string]*json.RawMessage after which verify your JSON file to see if it’s a string as an alternative.

I don’t have entry to the code. I hoped there was a solution to activate extra detailed logs like in Rust

I’m not conscious of any manner to do this in Go.

May you paste your JSON into a web-based JSON parser and see what the offending line is that manner? Additionally you might organize a fast take a look at utilizing the playground and attempt to debug it that manner. For instance, modify this playground hyperlink to have your precise JSON:

func foremost() {
	// Change this along with your JSON
	byt := []byte(`{ "value1": "take a look at", "value2": }`)
	var dat map[string]*json.RawMessage
	if err := json.Unmarshal(byt, &dat); err != nil {

The output from that’s a minimum of extra descriptive than what your executable is supplying you with:

panic: invalid character '}' in search of starting of worth

goroutine 1 [running]:
	/tmp/sandbox266866198/prog.go:13 +0xe7

Program exited.

You possibly can additionally attempt the process outlined right here together with that go playground hyperlink to get extra information:

Although as soon as once more, a web-based JSON parser ought to work effective to present you an in depth error message.

That helps if the JSON is invalid, however if you happen to put a JSON string worth the place an object is anticipated (e.g. {"key": "string"} vs {"key": {"subkey": "string"}}), I don’t suppose this may assist until you’ve got a JSON schema definition.

1 Like

Ah good name – I incorrectly assumed it was invalid JSON as a result of map[string]*json.RawMessage is fairly versatile (it may possibly deal with each the examples you talked about simply effective). However you’re completely proper – it’s legitimate JSON to have solely an array as top-level textual content:

And in that case, map[string] would break.

json.Unmarshall will return a *json.SyntaxError, which has an Offset subject, which comprises the variety of bytes efficiently learn earlier than the syntax error.


Most Popular

Recent Comments