英文:
Parsing JSON in Go (without Unmarshal)
问题
我需要在Golang中解析任意的JSON结构,以便将其转换为另一种语言格式(无论是C结构体还是XML),但是Golang库似乎通过将其编组和解组为结构体和映射来使这种操作变得不可能。
实际上,我甚至不需要从JSON输入中获得类似映射的数据结构。我只需要一个递归解析器,甚至可能类似于PHP的XMLParser,在每个节点上自己决定要做什么,这样我就可以在不需要映射或接口的情况下进行翻译。
英文:
I need to parse arbitrary JSON structures in Golang for the sake of translating them into another language format (whether it be C structs or XML), but the Golang library apparently makes this impossible to do with Marshalling and Unmarshalling into structs and maps.
I don't necessarily even need a map-like data structure from the JSON input anyway. All I need is a recursive parser, maybe even something like PHP's XMLParser where you decide what do do yourself at each node, so I can translate it without the need for maps or interfaces.
答案1
得分: 1
在megajson包中有一个scanner
包,它允许你自己遍历JSON。
scanner := scanner.NewScanner(strings.NewReader(`{"foo":"bar",
"bat":1293,"truex":true,"falsex":false,"nullx":null,"nested":{"xxx":"yyy"}}`))
// 扫描下一个JSON标记。
position, token, err := scanner.Scan()
请注意,这只是一个示例代码,你需要根据自己的需求进行适当的修改和使用。
英文:
There is a scanner
package in the megajson package that allows you to walk through the json yourself.
scanner := scanner.NewScanner(strings.NewReader(`{"foo":"bar",
"bat":1293,"truex":true,"falsex":false,"nullx":null,"nested":{"xxx":"yyy"}}`))
// Scan for the next JSON token.
position, token, err := scanner.Scan()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论