2019-03-06 01:09
浏览 510


Is there a simple way in Go to check whether given JSON is either an Object {} or array []?

The first thing that comes to mind is to json.Unmarshal() into an interface, and then see if it becomes a map, or a slice of maps. But that seems quite inefficient.

Could I just check if the first byte is a { or a [? Or is there a better way of doing this that already exists.

图片转代码服务由CSDN问答提供 功能建议

Go中是否有一种简单的方法来检查给定的JSON是否为Object {} 或数组 []

首先想到的是将 json.Unmarshal()插入接口,然后 然后查看它是否成为地图或地图切片。 但这似乎效率很低。

我可以检查一下第一个字节是 {还是 []吗? 还是有一种更好的方法可以做到这一点?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duancuan7057 2019-03-06 01:40

    Use the following the following to detect if JSON text in the []byte value data is an array or object:

     // Get slice of data with optional leading whitespace removed.
     // See RFC 7159, Section 2 for the definition of JSON whitespace.
     x := bytes.TrimLeft(data, " \t
     isArray := len(x) > 0 && x[0] == '['
     isObject := len(x) > 0 && x[0] == '{'

    This snippet of code handles optional leading whitespace and is more efficient than unmarshalling the entire value.

    Because the top-level value in JSON can also be a number, string, boolean or nil, it's possible that isArray and isObject both evaluate to false. The values isArray and isObject can also evaluate to false when the JSON is invalid.

    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题