如何检查字符串是否为json格式 [英] How to check string is in json format

查看:115
本文介绍了如何检查字符串是否为json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数来接收输入字符串,该字符串可以是json格式的字符串,也可以只是一个字符串.例如,以下功能很简单.

I want to create a function to receive an input string which can be string in json format or just a string. For example, something easy like following function.

func checkJson(input string){
   if ... input is in json ... {
      fmt.Println("it's json!")
   } else {
      fmt.Println("it's normal string!")
   }
}

推荐答案

我不清楚您是否仅需要了解带引号的字符串"或是否需要了解json或两者之间的区别,所以这向您展示了如何检测这两种情况,因此您可以非常具体.

I was unclear if you needed to know about just a "quoted string" or if you needed to know about json, or the difference between both of them, so this shows you how to detect both scenarios so you can be very specific.

我也在此处发布了交互式代码示例: http://play.golang.org/p/VmT0BVBJZ7

I posted the interactive code sample here as well: http://play.golang.org/p/VmT0BVBJZ7

package main

import (
    "encoding/json"
    "fmt"
)

func isJSONString(s string) bool {
    var js string
    return json.Unmarshal([]byte(s), &js) == nil

}

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

}

func main() {
    var tests = []string{
        `"Platypus"`,
        `Platypus`,
        `{"id":"1"}`,
    }

    for _, t := range tests {
        fmt.Printf("isJSONString(%s) = %v\n", t, isJSONString(t))
        fmt.Printf("isJSON(%s) = %v\n\n", t, isJSON(t))
    }

}

将输出以下内容:

isJSONString("Platypus") = true
isJSON("Platypus") = false

isJSONString(Platypus) = false
isJSON(Platypus) = false

isJSONString({"id":"1"}) = false
isJSON({"id":"1"}) = true

这篇关于如何检查字符串是否为json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆