2014-10-04 9 views
9

Realizzo un piccolo servizio Web in Nim e devo rispondere alle richieste con json. Sto usando il jester module per rendere il servizio. Mi aspetto che posso usare il modulo json nella libreria di base di Nim per costruire un qualche tipo di oggetto con campi e valori, e quindi convertirlo in una stringa json. Ma come? O c'è un modo migliore per costruire JSON in Nim?Come convertire un oggetto in JSON in Nim

risposta

10

In Nim si utilizza json module per creare JsonNode oggetti che sono object variants. Questi possono essere costruiti con i singoli proc come newJObject() e quindi compilare la sequenza fields. Un altro modo più rapido è utilizzare il %() proc che accetta una sequenza di tuple in cui un valore è la stringa con il campo JSON e l'altro il singolo JsonNode.

Ecco un esempio che mostra entrambi i modi:

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

Il modulo marshal comprende un algoritmo di serializzazione generica oggetto-to-JSON che funziona per qualsiasi tipo (tipo run-time attualmente, utilizza l'introspezione).

import marshal 

type 
    Person = object 
    age: int 
    name: string 

var p = Person(age: 38, name: "Torbjørn") 

echo($$p) 

L'uscita sarà:

{"age": 38, "name": "Torbj\u00F8rn"} 
+0

Mentre Grzegorz risposta era proprio quello che cercavo, questa risposta è stato anche molto utile, interessante e più semplice rispetto all'utilizzo del modulo json. Freddo! –

+0

Sembra che in Nim tutti facciano gli operatori? – PascalVKooten

2

Un'altra opzione descritta da me here è quello di effettuare le seguenti operazioni:

import json 

var jsonResponse = %* 
        {"data": [{ "id": 35, 
           "type": "car", 
           "attributes": {"color":"red"} }]} 

var body = "" 

toUgly(body, jsonResponse) 

echo body