在golang中解析数组JSON

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

Unmarshal array json in golang

问题

如何解组类似以下结构的数据:

[
	2,
	"19223201",
	"SomeString",
	{
		"SomeField": "FieldValue",
		"SomeField2": "FieldValue2",
		"SomeFieldN": "FieldValueN"
	}
]
英文:

How would I unmarshal something like this:

[
2,
"19223201",
"SomeString",
{
	"SomeField": "FieldValue",
	"SomeField2": "FieldValue2", "SomeFieldN": "FieldValueN",   	}
]

答案1

得分: 0

你可以使用interface{}类型,如果你没有定义任何接口,并将其解组为接口类型的切片。

import (
	"fmt"
	"encoding/json"
)

func main() {

	strBytes := []byte(`[2,"19223201", "SomeString",{"SomeField": "FieldValue","SomeField2": "FieldValue2", "SomeFieldN": "FieldValueN"}]`)
	keys := make([]interface{},0)

	json.Unmarshal(strBytes, &keys)
	fmt.Println(keys)
	
}

请注意,这段代码是用Go语言编写的。

英文:

You can use interface{} if you have not define any interface and unmarshal into interface type slice.

import (
	"fmt"
	"encoding/json"
)

func main() {

	strBytes := []byte(`[2,"19223201", "SomeString",{"SomeField": "FieldValue","SomeField2": "FieldValue2", "SomeFieldN": "FieldValueN"}]`)
	keys := make([]interface{},0)

	json.Unmarshal(strBytes, &keys)
	fmt.Println(keys)
	
}

huangapple
  • 本文由 发表于 2017年5月11日 20:21:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43915262.html
匿名

发表评论

匿名网友

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

确定