I'm playing around with JSON and a bit surprised at its behavior. I can't for the life of me figure out how to write a table out to JSON.
Example code:
import json
import std/jsonutils
import tables
var a = {1: "one", 2: "two"}.toTable
var j = toJson(a)
echo j
Expected output:
{1: "one", 2: "two"}.
Actual output:
{"data":[{"hcode":0,"key":0,"val":""},{"hcode":0,"key":0,"val":""},{"hcode":0,"key":0,"val":""},{"hcode":0,"key":0,"val":""},{"hcode":6130242188011939732,"key":2,"val":"two"},{"hcode":8641844181895329213,"key":1,"val":"one"},{"hcode":0,"key":0,"val":""},{"hcode":0,"key":0,"val":""}],"counter":2}
E2: There does seem to be a hook for tables, not sure what's wrong then... https://nim-lang.org/docs/jsonutils.html#toJsonHook
That's exactly why I was wondering. Seems like it should work out of the box which is why I was surprised.
{1: "one", 2: "two"} is not valid JSON, JSON keys must be strings. This works just fine:
import json
import std/jsonutils
import tables
var a = {"one": 1, "two": 2}.toTable
var j = jsonutils.toJson(a)
echo j
That's exactly why I was wondering. Seems like it should work out of the box which is why I was surprised.
=> see runnableExamples in https://github.com/nim-lang/Nim/pull/16062
block:
let a = {10: "foo", 11: "bar"}.newOrderedTable
let a2 = collect(newSeq): (for k,v in a: (k,v))
doAssert $toJson(a2) == """[[10,"foo"],[11,"bar"]]"""
# or pending #9217, simply:
let a2 = toSeq({10: "foo", 11: "bar"}.newOrderedTable)
...