json - Go JSON解析错误

标签 json go yaml

我正在用 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"`
}

Playground Example

关于json - Go JSON解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273806/

相关文章:

json - 如何使用 golang 将事件字段更改为非事件状态以保持字段值不变?

arrays - 在 Go 中解码顶级 JSON 数组

jenkins - 使用 groovy 在 jenkins 中编写 yaml 文件

amazon-web-services - CloudFormation 模板中不同 AWS Lambda 别名的环境变量配置

java - 有什么方法可以在 Spring 中使用 Swagger 包含 Controller 中未使用的类吗?

java - 使用 AtlasMap 将 xml 转换为 json

mysql - UnixNano 和 MySQL 用法的区别

json - Flutter从互联网上获取数据

c# - 如何使用 JsonProperty 获取嵌套属性

c# - 在 .NET 中过滤 IEnumerable 并将其序列化为 JSON 的有效方法