3 回答

TA貢獻1872條經驗 獲得超4個贊
使用以下代碼檢測值中的 JSON 文本[]byte是data數組還是對象:
// 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\r\n")
isArray := len(x) > 0 && x[0] == '['
isObject := len(x) > 0 && x[0] == '{'
這段代碼處理可選的前導空格,比解組整個值更有效。
因為 JSON 中的頂級值也可以是數字、字符串、布爾值或 nil,所以isArray和isObject都可能計算為 false。當 JSON 無效時,值isArray和也可以評估為 false。isObject

TA貢獻1993條經驗 獲得超6個贊
使用類型開關來確定類型。這類似于 Xay 的回答,但更簡單:
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
// handle error
}
switch v := v.(type) {
case []interface{}:
// it's an array
case map[string]interface{}:
// it's an object
default:
// it's something else
}

TA貢獻1817條經驗 獲得超14個贊
使用json.Decoder
.?這比其他答案有優勢:
比解碼整個值更有效
使用官方的 JSON 解析規則,如果輸入無效則生成標準錯誤。
請注意,此代碼未經測試,但應該足以讓您了解。如果需要,它還可以輕松擴展以檢查數字、布爾值或字符串。
func jsonType(in io.Reader) (string, error) {
? ? dec := json.NewDecoder(in)
? ? // Get just the first valid JSON token from input
? ? t, err := dec.Token()
? ? if err != nil {
? ? ? ? return "", err
? ? }
? ? if d, ok := t.(json.Delim); ok {
? ? ? ? // The first token is a delimiter, so this is an array or an object
? ? ? ? switch (d) {
? ? ? ? case '[':
? ? ? ? ? ? return "array", nil
? ? ? ? case '{':
? ? ? ? ? ? return "object", nil
? ? ? ? default: // ] or }, shouldn't be possible
? ? ? ? ? ? return "", errors.New("Unexpected delimiter")
? ? ? ? }
? ? }
? ? return "", errors.New("Input does not represent a JSON object or array")
}
請注意,這消耗了in. 如有必要,讀者可以復印一份。如果您嘗試從字節切片 ( ) 中讀取[]byte,請先將其轉換為讀取器:
t, err := jsonType(bytes.NewReader(myValue))
- 3 回答
- 0 關注
- 207 瀏覽
添加回答
舉報