dsfdsf8888 2017-06-27 05:54
浏览 89
已采纳

解组未知格式的JSON数据[重复]

This question already has an answer here:

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}
]
}

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(...)}]
}

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

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:"-"`
}
</div>
  • 写回答

1条回答 默认 最新

  • doubingjiu3199 2017-06-27 06:33
    关注
    • 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

    Option 1:

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

    Option 2: if you want have struct

    var gradesData GradeData
    err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
    fmt.Println(err)
    
    fmt.Printf("%#v
    ", gradesData)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于python拓展屏使用pyautogui.screenshot无法截图的问题
  • ¥15 有偿求答 无导出权限怎么快速导出企业微信微文档
  • ¥15 求解答,怎么数码管中这么加入闹钟或者传感器,这应该怎么加入相应的代码
  • ¥15 scottplot5
  • ¥30 想问问这个建模怎么编程没有思路
  • ¥15 关于imageENview(ImageEN)中新建图层并根据鼠标位置添加图标
  • ¥100 用两台电脑局域联网进行MT5的EA参数优化,但是连接不上,日志提示:
  • ¥15 FastAPI报错: AsyncSession不是有效Pydantic类型
  • ¥50 这Mac系统提示虚拟内存不足,怎么解决
  • ¥15 Rs232电路无法收发数据,求帮助