普通网友 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 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题