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!")
   }
}

推荐答案

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

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))
    }

}

Which will output this:

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

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

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

Json相关问答推荐

Postgres Select json数组并重新映射属性名称

使用Kotlin限制序列化类属性的允许整数值

无法访问id的第三级json

Jolt Spec 跳过数组中的第一个元素

未知的META规范,无法验证.[规范v1.0.1]

如何使用jolt规范将一个对象添加到另一个对象中并删除该对象

使用 map_values Select 包含空格的字符串未按预期工作

阅读 JSON 正文 Firebase 云函数

如何从条带订阅响应对象中正确获取 struct 项?

坚持弄清楚如何使用 api 响应来调用以从不同的链接检索响应

如果有 1 个元素,如何防止 ConvertFrom-Json 折叠嵌套数组

如何在生产环境中更改 Flutter 应用程序中的数据模型?

如何让 JSON.NET 忽略对象关系?

Json.NET SerializeObject 转义值以防止 XSS

如何为所有 API 端点全局设置 http.ResponseWriter Content-Type 标头?

以 unicode 将 pandas DataFrame 写入 JSON

JSON对象中的JavaScript递归搜索

如何按键查找特定的 JSON 值?

在 React 中访问子级的父级状态

无法将 System.String 转换或转换为 Class 对象