Parsing JSON in Go (without Unmarshal)

huangapple go评论91阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2014年4月2日 02:27:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/22793942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定