在Golang中进行JSON数组字符串转换

huangapple go评论89阅读模式
英文:

JSON array string conversion in Golang

问题

我有一个类似的JSON数组字符串,

str = '[{"a":"1","b":"1"},{"a":"2","b":"2"}]'

在JavaScript中,我可以轻松解析它。

let data = JSON.parse(str)
// data是一个包含两个元素的数组 [{a:"1", b:"1"}, {a:"2", b:"2"}]

在Golang中,我该如何解析这个字符串?
最终,我想要验证该字符串是否符合JSON格式(对象或数组)。

英文:

I have a JSON array string like,

str = '[{"a":"1","b":"1"},{"a":"2","b":"2"}]'

In JS, I can parse it easily.

let data = JSON.parse(str)
// data is ARRAY[2] [{a:"1", b:"1"}, {a:"2", b:"2"}]

In Golang, how can I parse the string?

Eventually I'd like to validate whether the string is JSON format(object or array) or not.

答案1

得分: 1

在Go语言中,你可以尝试将数据解组成你感兴趣的两种类型进行测试 - 数组(切片)和对象(映射)。以下代码将运行两个测试,分别测试你想要测试的每种类型。


import (
	"encoding/json"
	"fmt"
)

func main() {
	tests := [][]byte{
		[]byte(`[{"a":"1","b":"1"},{"a":"2","b":"2"}]`),
		[]byte(`{"a":"1","b":[{"a":1,"b":2}]}`),
	}

	for _, test := range tests {
		kind, err := getKind(test)
		if err != nil {
			fmt.Printf("Error: %s\n", err)
			continue
		}
		fmt.Printf("%s is type %s\n", string(test), kind)

	}
}

func getKind(d []byte) (string, error) {
	var a []interface{}
	var m map[string]interface{}
	var e error

	e = json.Unmarshal(d, &a)
	if e != nil {
		e = json.Unmarshal(d, &m)
		if e != nil {
			return "", e
		}
		return "map", nil
	}
	return "array", nil
}

输出

[{"a":"1","b":"1"},{"a":"2","b":"2"}] is type array
{"a":"1","b":[{"a":1,"b":2}]} is type map
英文:

In Go you would try to unmarshal your data into each of the two types you are interested in testing - array (slice), and object (map). This code will run two tests, one of each type you wanted to test for.


import (
	"encoding/json"
	"fmt"
)

func main() {
	tests := [][]byte{
		[]byte(`[{"a":"1","b":"1"},{"a":"2","b":"2"}]`),
		[]byte(`{"a":"1","b":[{"a":1,"b":2}]}`),
	}

	for _, test := range tests {
		kind, err := getKind(test)
		if err != nil {
			fmt.Printf("Error: %s\n", err)
			continue
		}
		fmt.Printf("%s is type %s\n", string(test), kind)

	}
}

func getKind(d []byte) (string, error) {
	var a []interface{}
	var m map[string]interface{}
	var e error

	e = json.Unmarshal(d, &a)
	if e != nil {
		e = json.Unmarshal(d, &m)
		if e != nil {
			return "", e
		}
		return "map", nil
	}
	return "array", nil
}

OUTPUT

[{"a":"1","b":"1"},{"a":"2","b":"2"}] is type array
{"a":"1","b":[{"a":1,"b":2}]} is type map

答案2

得分: 1

package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

func main() {
	tests := [][]byte{
		[]byte(`[{"a":"1","b":"1"},{"a":"2","b":"2"}]`),
		[]byte(`{"a":"1","b":[{"a":1,"b":2}]}`),
	}
	for _, b := range tests {
		var v interface{}
		err := json.Unmarshal(b, &v)
		if err != nil {
			return
		}
		// 使用反射或者switch-case
		fmt.Println(string(b), "类型是:", reflect.TypeOf(v))

		switch val := v.(type) {
		case []interface{}:
			fmt.Println(val, "是数组")
		case map[string]interface{}:
			fmt.Println(val, "是映射")
		}
	}
}

// 输出:
// [{"a":"1","b":"1"},{"a":"2","b":"2"}] 类型是: []interface {}
// [map[a:1 b:1] map[a:2 b:2]] 是数组
// {"a":"1","b":[{"a":1,"b":2}]} 类型是: map[string]interface {}
// map[a:1 b:[map[a:1 b:2]]] 是映射
英文:
package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

func main() {
	tests := [][]byte{
		[]byte(`[{"a":"1","b":"1"},{"a":"2","b":"2"}]`),
		[]byte(`{"a":"1","b":[{"a":1,"b":2}]}`),
	}
	for _, b := range tests {
		var v interface{}
		err := json.Unmarshal(b, &v)
		if err != nil {
			return
		}
		// use reflect or switch-case
		fmt.Println(string(b), "type is:", reflect.TypeOf(v))

		switch val := v.(type) {
		case []interface{}:
			fmt.Println(val, "is array")
		case map[string]interface{}:
			fmt.Println(val, "is map")
		}
	}
}

// output:
// [{"a":"1","b":"1"},{"a":"2","b":"2"}] type is: []interface {}
// [map[a:1 b:1] map[a:2 b:2]] is array
// {"a":"1","b":[{"a":1,"b":2}]} type is: map[string]interface {}
// map[a:1 b:[map[a:1 b:2]]] is map

huangapple
  • 本文由 发表于 2021年7月28日 09:12:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68553250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定