普通网友 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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同