我正在 Nim 中制作一个小型 Web 服务,我需要使用 json 响应请求。我正在使用jester 模块来提供服务。我希望我可以使用 Nim 基础库中的 json 模块来构造某种具有字段和值的对象,然后将其转换为 json 字符串。但是怎么做?或者有没有更好的方法在 Nim 中构造 json?
问问题
3257 次
4 回答
26
marshal 模块包括一个通用的 object-to-json 序列化算法,适用于任何类型(目前,它使用运行时类型自省)。
import marshal
type
Person = object
age: int
name: string
var p = Person(age: 38, name: "Torbjørn")
echo($$p)
输出将是:
{"age": 38, "name": "Torbj\u00F8rn"}
于 2014-10-04T16:37:09.563 回答
11
在 Nim 中,您使用json 模块来创建JsonNode
作为对象变体的对象。这些可以用像newJObject()这样的单独的过程来构造,然后填充fields
序列。另一种更快的方法是使用%() proc,它接受一个元组序列,其中一个值是带有 json 字段的字符串,另一个是 individual JsonNode
。
这是一个显示两种方式的示例:
import json
type
Person = object ## Our generic person record.
age: int ## The age of the person.
name: string ## The name of the person.
proc `%`(p: Person): JsonNode =
## Quick wrapper around the generic JObject constructor.
result = %[("age", %p.age), ("name", %p.name)]
proc myCustomJson(p: Person): JsonNode =
## Custom method where we replicate manual construction.
result = newJObject()
# Initialize empty sequence with expected field tuples.
var s: seq[tuple[key: string, val: JsonNode]] = @[]
# Add the integer field tuple to the sequence of values.
s.add(("age", newJInt(p.age)))
# Add the string field tuple to the sequence of values.
s.add(("name", newJString(p.name)))
result.fields = s
proc test() =
# Tests making some jsons.
var p: Person
p.age = 24
p.name = "Minah"
echo(%p) # { "age": 24, "name": "Minah"}
p.age = 33
p.name = "Sojin"
echo(%p) # { "age": 33, "name": "Sojin"}
p.age = 40
p.name = "Britney"
echo p.myCustomJson # { "age": 40, "name": "Britney"}
when isMainModule: test()
于 2014-10-04T10:17:05.183 回答
5
marshal
对于在此线程中找到基于 - 答案的任何其他人。改用这个:
import json
type
Person = object
age: int
name: string
var p = Person(age: 38, name: "Torbjørn")
echo(%p)
请注意,您不应该将其marshal
用于此目的,它相当于pickle
Python 中的模块,它可能会生成包含您可能不想要的额外数据的 JSON。另外,现在生成JSON只是巧合,以后可能会选择不同的格式。
于 2020-08-21T16:26:46.830 回答
2
请执行下列操作:
import json
var jsonResponse = %*
{"data": [{ "id": 35,
"type": "car",
"attributes": {"color":"red"} }]}
var body = ""
toUgly(body, jsonResponse)
echo body
于 2016-06-27T18:34:45.823 回答