gpt4 book ai didi

nim-lang - 如何在 Nim 中将对象序列转换为 JSON?

转载 作者:行者123 更新时间:2023-12-05 06:12:56 25 4
gpt4 key购买 nike

我正在尝试将对象列表转换为 JSON,但无法正确序列化

import marshal

type
DocItem = object of RootObj
tags: seq[string]

TextDoc = object of DocItem
text: string

TodoDoc = object of DocItem
todo: string

var docs: seq[ref DocItem]

proc to_ref[T](o: T): ref T =
result.new
result[] = o

docs.add TextDoc(text: "some doc", tags: @["help"]).to_ref
docs.add TodoDoc(todo: "some todo").to_ref

echo $$docs

输出是:

[[4312834120, {"tags": ["help"]}], [4312834280, {"tags": []}]]

当我需要它的时候

[{"text": "some doc", "tags": ["help"]}, {"todo": "some todo", "tags": []}]

还有,有没有办法配置marshal输出漂亮的JSON?

最佳答案

不幸的是,编码似乎是正确的:它显示了指向 ref Object 的指针。也许您可以求助于组合而不是继承:

import marshal


type
Todo = object of RootObj
todo: string

Text = object of RootObj
text: string

DocItem = object of RootObj
tags: seq[string]
text: Text
todo: Todo

var docs: seq[DocItem] = @[]

docs.add DocItem(tags: @["help"], todo: Todo(todo: "some todo"))
docs.add DocItem(tags: @["help"], text: Text(text: "some text"))

echo $$docs

或者您可以尝试 object variants .我正在添加一个新的虚构的“链接”类型来更好地说明它:

import marshal


type
Content = enum
tTodo
tText
tImage

DocItem = object of RootObj
tags: seq[string]
case kind: Content
of tTodo, tText:
text: string
of tLink:
url: string

var docs: seq[DocItem] = @[]

docs.add DocItem(tags: @["help"], kind: tTodo, todoVal: "some todo")
docs.add DocItem(tags: @["help"], kind: tText, textVal: "some text")
docs.add DocItem(tags: @["help"], kind: tLink, url: "http://stackoverflow.com")

echo $$docs

关于nim-lang - 如何在 Nim 中将对象序列转换为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63492720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com