解组未知格式的JSON数据 [英] Unmarshal JSON data of unknown format

查看:128
本文介绍了解组未知格式的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON格式如下:

My JSON is in the following format:

{
'Math': 
[
    {'Student1': 100.0, 'timestamp': Timestamp('2017-06-26 15:30:00'), 'Student2': 100.0, 'Student3': 97.058823442402414},
    {'Student1': 93.877550824911907, 'timestamp': Timestamp('2017-06-26 15:31:00'), 'Student2': 100.0, 'Student5': 100.0},
    {'Student8': 100.0, 'timestamp': Timestamp('2017-06-26 15:32:00'), 'Student10': 100.0, 'Student4': 100.0}
],
'English': [
    {'Student1': 100.0, 'timestamp': Timestamp('2017-06-26 15:30:00'), 'Student5': 100.0, 'Student3': 97.058823442402414},
    {'Student1': 93.877550824911907, 'timestamp': Timestamp('2017-06-26 15:31:00'), 'Student2': 100.0, 'Student5': 100.0}, 
    {'Student8': 100.0, 'timestamp': Timestamp('2017-06-26 15:32:00'), 'Student10': 100.0, 'Student4': 100.0}
]
}

键是我完全不知道的.我所知道的是JSON的格式为:

The keys are completely unknown to me. All I know is that the JSON will be of the format:

{
SUBJECT1: [{Student_Name1: Grade, Student_Name2: Grade, ... , Student_Name3: Grade, timestamp: Timestamp(...)}],
SUBJECT2: [{Student_Name4: Grade, Student_Name6: Grade, ... , Student_Name5: Grade, timestamp: Timestamp(...)}]
...
SUBJECTN: [{Student_Name1: Grade, Student_Name6: Grade, ... , Student_Name9: Grade, timestamp: Timestamp(...)}]
}

其中subjectsstudent_names都是未知的,并且可能会有所不同.

where the subjects, student_names are all unknown and could vary.

我想将其解组为GoLang结构,以便将其作为JSON对象返回到前端.我的结构应该是什么样的?这是我尝试过的方法,但是没有用.

I want to unmarshal this into a GoLang struct so I can return it to my front-end as a JSON object. What should my struct look like? This is what I tried, but it didn't work.

type GradeData struct {
    Grades map[string]interface{} `json:"-"`
}

推荐答案

  • 如果您不知道密钥,则可以使用map[string]interface{}解组JSON有效负载.
  • 如果对struct字段使用json:"-"标签,则在JSON元帅/反元帅期间这些字段将被忽略.
    • If you don't know the keys, you can use map[string]interface{} to unmarshal your JSON payload.
    • If you use json:"-" tag for the struct fields, those fields will be ignored during JSON Marshal/Unmarshal.
    • 您可以尝试以下选项:转到游乐场链接

      You can try following options: Go Playground link

      选项1:

      var grades map[string]interface{}
      
      err := json.Unmarshal([]byte(jsonString), &grades)
      fmt.Println(err)
      
      fmt.Printf("%#v\n", grades)
      

      选项2:(如果您想拥有struct

      var gradesData GradeData
      err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
      fmt.Println(err)
      
      fmt.Printf("%#v\n", gradesData)
      

      这篇关于解组未知格式的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆