Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think I'd want to try to decode into map[string]interface{} (offhand), since string keys can be coerced to that in any event (they're strings in the stream, quoted or otherwise), and a key can hold any valid json scalar, array, or object (another json sub-string).


That of course works, but the problem is then using this. Take a simple JSON like `{"list": [{"field": 8}]}`. To retrieve that value of 8, your Go code will look sort of like this:

  var v map[string]any
  json.Unmarshal(myjson, &v)
  lst := v["list"].([]any)
  firstItem := lst[0].(map[string]any)
  field := firstItem["field"].(float64)
And this is without any error checking (this code will panic if myjson isn't a json byte array, if the keys and types don't match, or if the list is empty). If you want to add error checking to avoid panics, it gets much longer [0].

Here is the equivalent Python with full error checking:

  try :
    v = json.loads(myjson)
    field = v["list"][0]["list"]
  except Exception as e:
    print(f"Failed parsing json: {e}")
[0] https://go.dev/play/p/xkspENB80JZ




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: