2023-12-13 09:07:57 +00:00
|
|
|
# json-serialization
|
|
|
|
# Copyright (c) 2019-2023 Status Research & Development GmbH
|
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
# at your option.
|
|
|
|
# This file may not be copied, modified, or distributed except according to
|
|
|
|
# those terms.
|
|
|
|
|
2023-12-18 04:05:12 +00:00
|
|
|
import
|
|
|
|
std/strutils,
|
|
|
|
stew/shims/tables,
|
|
|
|
../../json_serialization/[reader, writer, lexer]
|
|
|
|
|
2019-08-02 10:25:02 +00:00
|
|
|
export tables
|
|
|
|
|
|
|
|
type
|
|
|
|
TableType = OrderedTable | Table
|
|
|
|
|
2023-08-19 11:47:32 +00:00
|
|
|
proc writeValue*(
|
|
|
|
writer: var JsonWriter, value: TableType) {.raises: [IOError].} =
|
2019-08-02 10:25:02 +00:00
|
|
|
writer.beginRecord()
|
|
|
|
for key, val in value:
|
2020-05-08 13:12:29 +00:00
|
|
|
writer.writeField $key, val
|
2019-08-02 10:25:02 +00:00
|
|
|
writer.endRecord()
|
|
|
|
|
2020-05-08 13:12:29 +00:00
|
|
|
template to*(a: string, b: typed): untyped =
|
|
|
|
{.error: "doesnt support keys with type " & $type(b) .}
|
|
|
|
|
|
|
|
template to*(a: string, b: type int): int =
|
|
|
|
parseInt(a)
|
|
|
|
|
|
|
|
template to*(a: string, b: type float): float =
|
|
|
|
parseFloat(a)
|
|
|
|
|
|
|
|
template to*(a: string, b: type string): string =
|
|
|
|
a
|
|
|
|
|
2019-08-02 10:25:02 +00:00
|
|
|
proc readValue*(reader: var JsonReader, value: var TableType) =
|
2023-06-05 08:23:36 +00:00
|
|
|
try:
|
|
|
|
type KeyType = type(value.keys)
|
|
|
|
type ValueType = type(value.values)
|
|
|
|
value = init TableType
|
|
|
|
for key, val in readObject(reader, string, ValueType):
|
|
|
|
value[to(key, KeyType)] = val
|
|
|
|
except ValueError as ex:
|
|
|
|
reader.raiseUnexpectedValue("TableType: " & ex.msg)
|