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 ]

JSON: read a list of numbers

Nim supports the JSON format natively, it's in the standard library.

Read a list of numbers

Say we have a file that contains a list of integers. The task is the following: read it into a seq[int].

short.json :

[171, 190, 180, 193, 180]

Ver. 1: parseFile()

import std/strutils    # strip, split, join
import std/json


proc main() =
  let
    parsed: JsonNode = parseFile("short.json")
    numbers: seq[int] = parsed.to(seq[int])

  echo numbers    # @[171, 190, 180, 193, 180]

main()

A JsonNode is Nim's universal JSON value type — it can hold any JSON value. We specify the filename, its content is read to a universal JSON type, which is parsed to a specific Nim type, namely to seq[int].

Ver. 2: readFile()

Let's see how to convert a JSON string to a native Nim type.

Suppose we've already read the content of a JSON file and we have the content as a string. Thus, having a JSON string, how to convert it to a native Nim type?

import std/strutils    # strip, split, join
import std/json


proc main() =
  let
    content: string = readFile("short.json")
    parsed: JsonNode = parseJson(content)
    numbers: seq[int] = parsed.to(seq[int])

  echo numbers    # @[171, 190, 180, 193, 180]

main()

We could also simplify it to two lines:

let
  content: string = readFile("short.json")
  numbers: seq[int] = parseJson(content).to(seq[int])
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 27, 20:52