Hi yall,
maybe i am wrong but when i list all keys from a json-node thru json.nim, i only get the unique-ified keys, but not the doubles.
Firstly i find that supprising and also it looks like a fault-tolerant approach. Non-unique keys are tolerated and ignored. More logical to me would be to include them, so that doubles can be seen and adressed.
But when i accept that approach, is there is json.nim-native way to show possible double keys? Or must you parse for them yourself, non-natively?
Thanx in advance.
The last value is used. See also https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object
You can easily use the raw JSON parser directly and implement any policy that you need if you duplicated keys but I would first see if the duplicated keys can be avoided entirely.
Thanx. I agree that double keys are unwise; that is exactly why i want to (automatically) detect them instead of ignoring them because i know i make mistakes. (Programmers want do it automatically :-) ).
So where do i find this raw parser?
You can do this with a jsony ( https://github.com/treeform/jsony ) parse hook:
type Header = object
key: string
value: string
proc parseHook(s: string, i: var int, v: var seq[Header]) =
eatChar(s, i, '{')
while i < s.len:
eatSpace(s, i)
if i < s.len and s[i] == '}':
break
var key, value: string
parseHook(s, i, key)
eatChar(s, i, ':')
parseHook(s, i, value)
v.add(Header(key: key, value: value))
eatSpace(s, i)
if i < s.len and s[i] == ',':
inc i
else:
break
eatChar(s, i, '}')
let data3 = """{
"Cache-Control": "private, max-age=0d",
"Content-Encoding": "brd",
"Set-Cookie": "name=valued",
"Set-Cookie": "name=value; name2=value2; name3=value3d"
}"""
let headers = data3.fromJson(seq[Header])
doAssert headers[0].key == "Cache-Control"
doAssert headers[0].value == "private, max-age=0d"
doAssert headers[1].key == "Content-Encoding"
doAssert headers[1].value == "brd"
doAssert headers[2].key == "Set-Cookie"
doAssert headers[2].value == "name=valued"
doAssert headers[3].key == "Set-Cookie"
doAssert headers[3].value == "name=value; name2=value2; name3=value3d"