普通网友 2018-02-14 00:27
浏览 1077
已采纳

检查字符串是否为JSON格式

How to check if a given string is in form of multiple json string separated by spaces/newline?

For example,
given: "test" 123 {"Name": "mike"} (3 json concatenated with space)
return: true, since each of item ("test" 123 and {"Name": "mike"}) is a valid json.

In Go, I can write a O(N^2) function like:

// check given string is json or multiple json concatenated with space/newline
func validateJSON(str string) error {
    // only one json string
    if isJSON(str) {
        return nil
    }
    // multiple json string concatenate with spaces
    str = strings.TrimSpace(str)
    arr := []rune(str)
    start := 0
    end := 0
    for start < len(str) {
        for end < len(str) && !unicode.IsSpace(arr[end]) {
            end++
        }
        substr := str[start:end]
        if isJSON(substr) {
            for end < len(str) && unicode.IsSpace(arr[end]) {
                end++
            }
            start = end
        } else {
            if end == len(str) {
                return errors.New("error when parsing input: " + substr)
            }
            for end < len(str) && unicode.IsSpace(arr[end]) {
                end++
            }
        }
    }
    return nil
}

func isJSON(str string) bool {
    var js json.RawMessage
    return json.Unmarshal([]byte(str), &js) == nil
}

But this won't work for large input.

  • 写回答

3条回答 默认 最新

  • douyangquan2474 2018-02-14 09:17
    关注

    There are two options. The simplest, from a coding standpoint, is going to be just to decode the JSON string normally. You can make this most efficient by decoding to an empty struct:

    package main
    
    import "encoding/json"
    
    func main() {
        input := []byte(`{"a":"b", "c": 123}`)
        var x struct{}
        if err := json.Unmarshal(input, &x); err != nil {
            panic(err)
        }
    
        input = []byte(`{"a":"b", "c": 123}xxx`) // This one fails
        if err := json.Unmarshal(input, &x); err != nil {
            panic(err)
        }
    }
    

    (playground link)

    This method has a few potential drawbacks:

    • It only works with a single JSON object. That is, a list of objects (as requested in the question) will fail, without additional logic.
    • As pointed out by @icza in comments, it only works with JSON objects, so bare arrays, numbers, or strings will fail. To accomodate these types, interface{} must be used, which introduces the potential for some serious performance penalties.
    • The throw-away x value must still be allocated, and at least one reflection call is likely under the sheets, which may introduce a noticeable performance penalty for some workloads.

    Given these limitations, my recommendation is to use the second option: loop through the entire JSON input, ignoring the actual contents. This is made simple with the standard library json.Decoder:

    package main
    
    import (
        "bytes"
        "encoding/json"
        "io"
    )
    
    func main() {
            input := []byte(`{"a":"b", "c": 123}`)
            dec := json.NewDecoder(bytes.NewReader(input))
            for {
                _, err := dec.Token()
                if err == io.EOF {
                    break // End of input, valid JSON
                }
                if err != nil {
                    panic(err) // Invalid input
                }
            }
    
            input = []byte(`{"a":"b", "c": 123}xxx`) // This input fails
            dec = json.NewDecoder(bytes.NewReader(input))
            for {
                _, err := dec.Token()
                if err == io.EOF {
                    break // End of input, valid JSON
                }
                if err != nil {
                    panic(err) // Invalid input
                }
            }
    }
    

    (playground link)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式