下面是一个json格式数据的示例:python
{ "id":1, "content":"hello world", "author":{ "id":2, "name":"userA" }, "published":true, "label":[], "nextPost":null, "comments":[ { "id":3, "content":"good post1", "author":"userB" }, { "id":4, "content":"good post2", "author":"userC" } ] }
用注释分析这个json:json
{ # 对象容器,下面全是这个对象中的属性。注意key全都是字符串 "id":1, # 文章ID号,元素,value类型为number "content":"hello world", # 文章内容 "author":{ # 子对象,文章做者 "id":2, # 做者ID "name":"userA" # 做者名称,注意子容器结束,没有逗号 }, "published":true, # 文章是否发布,布尔类型 "label":[], # 文章标签,没有给标签,因此空数组 "nextPost":null, # 下一篇文章,是对象,由于没有,因此为null "comments":[ # 文章评论,由于可能有多条评论,每条评论都是一个对象结构 { # 对象容器,表示评论对象 "id":3, # 评论的ID号 "content":"good post1", # 评论的内容 "author":"userB" # 评论者 }, { "id":4, "content":"good post2", "author":"userC" } ] }
通常来讲,json格式转换成语言中的数据结构时,有如下几个比较通用的规则(只是比较普通的方式,并不是必定):数组
例如,上面的示例,转换成Go中的数据结构时,获得的结果以下:数据结构
// 使用名称A代替顶层的匿名对象 type A struct { ID int64 `json:"id"` Content string `json:"content"` Author Author `json:"author"` Published bool `json:"published"` Label []interface{} `json:"label"` NextPost interface{} `json:"nextPost"` Comments []Comment `json:"comments"` } type Author struct { ID int64 `json:"id"` Name string `json:"name"` } type Comment struct { ID int64 `json:"id"` Content string `json:"content"` Author string `json:"author"` }
好比转换成python中的数据时,获得的结果以下:工具
from typing import List, Any class Author: id: int name: str def __init__(self, id: int, name: str) -> None: self.id = id self.name = name class Comment: id: int content: str author: str def __init__(self, id: int, content: str, author: str) -> None: self.id = id self.content = content self.author = author # 使用了名称A代替顶层的匿名对象 class A: id: int content: str author: Author published: bool label: List[Any] next_post: None comments: List[Comment] def __init__(self, id: int, content: str, author: Author, published: bool, label: List[Any], next_post: None, comments: List[Comment]) -> None: self.id = id self.content = content self.author = author self.published = published self.label = label self.next_post = next_post self.comments = comments
quicktype工具,能够轻松地将json文件转换成各类语言对应的数据结构。post
地址:https://quicktype.ioui
在vscode中有相关插件插件