Hi guys, I'm trying to save time series data to disk as JSON and then read it.
EconomicRatesM* = object
name*: string
rates_m*: seq[(string, float)]
But it won't work either way error when saving or reading, how can I fix it?
The code (executable in playground)
import json
type
SerieItem* = (string, float)
Serie* = seq[SerieItem]
EconomicRatesM* = object
name*: string
rates_m*: Serie
# Parsing
block:
let json_string = """
{
"name": "cpi",
"rates_m": [
["2020-01", 1],
["2020-02", 2]
]
}
"""
var json_data = parse_json(json_string)
var data = to(json_data, EconomicRatesM)
# Writing
block:
let data = EconomicRatesM(
name: "cpi",
rates_m: @[
("2020-01", 1.0),
("2020-02", 2.0),
]
)
echo %data
It's possible to use manual conversion, but it's not the best approach...
EconomicRatesM(
name: json["name"].get_str,
rates_m: json["rates_m"].get_elems.map((point) => (
point.get_elems[0].get_str,
point.get_elems[1].get_float,
)),
version: json["version"].get_int,
timestamp: json["timestamp"].get_int
)
@alexeypetrushin
Are you in some way related to the strange guy that pollutes stackoverflow with Nim questions? At least that guy have copied some of your forum post as
https://forum.nim-lang.org/t/6700
to
https://stackoverflow.com/questions/63492720/how-to-convert-sequence-of-objects-to-json-in-nim
"pollutes", "strange" Come on, dude. God forbid someone asks questions on StackBloodyOverflow
Not cool
Are you in some way related to the strange guy that pollutes stackoverflow with Nim questions?
I asked question on StackOverflow and after a day when there were no answer copied it to this forum. The copies of answers on StackOverflow were posted later.
Also, I was not sure what is the proper way, as there seems to be around 3 ways in Nim to work with JSON and some are not working as expected
the issue with the json module is you can specify % to convert TO json, but afaik there is no way to automatically convert it back. So you unfortunately cannot specify the inverse function of %.
It seems like overriding init_from_json works, although it's not documented.
Yes sorry, my assumption was that there is someone at stackoverflow who tries to damage the Nim language with a flood of questions. And indeed user names differ?
Unfortunately Nim is a weak target due to small user base, so question flood can generate the impression that language is death, and is at the same time a way to block most Nim devs if they answer, or to show the death state if there is no answer. And the high quantity of questions at the time suggests that the language is fully undocumented or not used by bright people.
So stack overflow attack can be indeed be a dangerous weapon -- large communities can defend it well.