Why I can't unmarshal JSON with spaces in the JSON keys?
import json
type
FooBar = object
`Foo Bar`: string
const jsonString = "{\"Foo Bar\": \"Hello World\"}"
let foobar = to(parseJson(jsonString), FooBar)
Is this a bug of Nim or am I missed something?
interesting, it's that Foo Bar is not the internal name for that member, it gets converted to FooBar
type
Foo = object
`Foo Bar`: string
#FooBar: string # error attempt to redefine FooBar
var x:Foo
x.FooBar = "world"
assert x.FooBar = "world"
so it's impossible to unpack a field containing a space to an object.you could use a Table[string,string] instead
import json,tables
const jsonString = "{\"Foo Bar\": \"Hello World\"}"
let foobar = to(parseJson(jsonString), Table[string,string])
assert foobar["Foo Bar"] == "Hello World"
Your answer is good, but it's missing the case if we don't have a pure string-string mapping. In that case, we can do it this way:
import json,tables
const jsonString = "{\"Foo Bar\": \"Hello World\"}"
let foobar = to(parseJson(jsonString), Table[string,JsonNode])
doAssert foobar["Foo Bar"].getStr() == "Hello World"
Jsony with a rename hook:
import jsony
type
FooBar = object
`Foo Bar`: string
const jsonString = "{\"Foo Bar\": \"Hello World\"}"
proc renameHook*(v: var FooBar, fieldName: var string) =
if fieldName == "Foo Bar":
fieldName = "FooBar"
echo jsonString.fromJson(FooBar)
Jsony is a very fast json parser with hooks https://github.com/treeform/jsony