Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ◇C++, ◇Clojure, ◇Scala


[ edit | logout ]
[ sandbox | passwd ]

Create a JSON file

With 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 literal

import 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
  • %* is a macro that constructs a JsonNode from a literal
  • doc.pretty converts a JsonNode to a nicely formatted string

Build JSON programatically

Let'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 seq

import 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 object

import 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
}
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 26, 23:00