我正在用 Golang 编写我的第一个程序,或者更确切地说,如果您愿意的话,我正在修改一个模板。想要解析 yaml 文件中的值。
apiVersion: "backend.example.com/v1alpha1"
kind: "Example"
metadata:
name: "solar-demo"
spec:
size: 2
group: backend.example.com
names:
kind: Example
listKind: ExampleList
plural: solar-demos
singular: solar-demo
scope: Namespaced
version: v1alpha1
pods:
- name: api
image: "shmukler/docker_solar-api"
port: 3000
command: '{"npm", "run", "start-api"}'
- name: service
image: "shmukler/docker_solar-svc"
port: 3001
command: '{"npm", "run", "start-solar-svc"}'
为了解析出变量,我这样做:
type Example struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
Spec ExampleSpec `json:"spec"`
Status ExampleStatus `json:"status,omitempty"`
}
type ExampleSpec struct {
Size int32 `json:"size"`
// Pods []ExamplePod `json:"pods"`
}
type ExampleStatus struct {
Nodes []string `json:"nodes"`
}
type ExamplePod struct {
Name []string `json:"name"`
Image []string `json:"image"`
Port int32 `json:"port"`
Command []string `json:"command"`
}
如果我注释掉 Pods []ExamplePod
行,尽管没有解析 Pods 数组,代码仍然有效。如果我把它留在里面,就会出现错误,只要我通过 yaml
文档 - Observed a panic: &errors.errorString{s:"failed to decode json data with gvk.. .
我想将 pods
粘贴到 ExamplePod
类型的结构数组中。
今天是我使用 Go 语言的第一天。对不起,一个愚蠢的问题。我的 yaml,JSON
表示中的相关片段。
spec":{
"group":"backend.example.com",
"names":{
"kind”:”Example”,
"listKind”:”ExampleList",
"plural":"solar-demos",
"singular":"solar-demo"
},
"pods":[
{
"command":"{\"npm\", \"run\", \"start-api\"}",
"image":"shmukler/docker_solar-api",
"name":"api",
"port":3000
},
{
"command":"{\"npm\", \"run\", \"start-solar-svc\"}",
"image":"shmukler/docker_solar-svc",
"name":"service",
"port":3001
}
],
"scope":"Namespaced",
"size":2,
"version":"v1alpha1"
}
我能够得到 example.Spec.Size
就好了。我缺少的是 pods
数组。
最佳答案
JSON 无效。将 ”
替换为 "
并添加周围的 {}
。
将 ExamplePod 字段的类型更改为字符串:
type ExamplePod struct {
Name string `json:"name"`
Image string `json:"image"`
Port int32 `json:"port"`
Command string `json:"command"`
}
关于json - Go JSON解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273806/