|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
Create a JSON fileWith your program, you want to create a JSON file. That is, you want to write some data to a file in JSON format. Build JSON from a literalimport std/json let doc: JsonNode = %* { "last": "Doe", "first": "John", "age": 39 } # v1 writeFile("doe.json", $doc) # write in a single line # v2 writeFile("doe.json", doc.pretty) # nicely indented output
Build JSON programaticallyLet's see how to build a JSON object without a literal. import std/json var doc = %* {} # empty JsonNode object doc["last"] = %* "Doe" doc["first"] = %* "John" doc["age"] = %* 39 echo doc # {"last":"Doe","first":"John","age":39} If you want, you can write it to a file. Let's see some more examples: Convert a seqimport std/json let primes: seq[int] = @[2, 3, 5, 7, 11] doc = %* primes writeFile("primes.json", $doc) # [2,3,5,7,11] (compact representation) Convert a custom objectimport std/json type Person = object last: string first: string age: int let p = Person(last: "Doe", first: "John", age: 39) doc = %* p echo p # (last: "Doe", first: "John", age: 39) echo doc # {"last":"Doe","first":"John","age":39} writeFile("person.json", doc.pretty)
$ cat person.json
{
"last": "Doe",
"first": "John",
"age": 39
}
|
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |