Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check string is in json format

Tags:

json

go

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!")    } } 
like image 381
A-letubby Avatar asked Mar 02 '14 13:03

A-letubby


People also ask

How do I check if a string is JSON?

All json strings start with '{' or '[' and end with the corresponding '}' or ']', so just check for that.

How do you check if a string is a JSON string in Java?

Let's write some tests to check the main cases: String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; assertTrue(validator. isValid(json)); String json = "[{\"email\": \"example@com\", \"name\": \"John\"}]"; assertTrue(validator.

Is string JSON format?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

How do I check if an object is in JSON format?

To check if JavaScript object is JSON, we can use the JSON. parse method. const isJson = (data) => { try { const testIfJson = JSON. parse(data); if (typeof testIfJson === "object") { return true; } else { return false; } } catch { return false; } };


2 Answers

For anyone else looking for a way to validate any JSON string regardless of schema, try the following:

func IsJSON(str string) bool {     var js json.RawMessage     return json.Unmarshal([]byte(str), &js) == nil } 
like image 102
William King Avatar answered Sep 26 '22 05:09

William King


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.

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

Which will output this:

isJSONString("Platypus") = true isJSON("Platypus") = false  isJSONString(Platypus) = false isJSON(Platypus) = false  isJSONString({"id":"1"}) = false isJSON({"id":"1"}) = true 
like image 28
Cory LaNou Avatar answered Sep 22 '22 05:09

Cory LaNou