Hi!
1) Is there something similar or equivalent in NIM for R function "fromJSON" from jsonlite R package. Let say my data is: one integer number and then 2 real numbers for each line coming from web. For example:
import json
# let's try with very short sintetic data
let datafromweb = "[[110, 33.4, 45.4], [120, 34.7, 23.6]]"
let jsonNode = parseJson(datafromweb)
Nim's parseJson spottedb the data just well.
Now, how to convert jsonNode nicely to a "dataframe" where first column is int, 2nd and 3rd columns are floats?
I even need to name the dataframe columns since my data have no name.
2)
Which dataframe to use? I.e., to which dataframe to convert? There are some libraries in Nim defining its own dataframe. Am I wrong? Nimdata, Arraymancer? Thank you
From the json module in the stdlib you have proc to[T](node: JsonNode; t: typedesc[T]): T which can convert Json to a type.
Doc : https://nim-lang.org/docs/json.html#to%2CJsonNode%2Ctypedesc%5BT%5D
For further versatility you have : https://nim-lang.org/docs/jsonutils.html
As external third parties, there are some excellent choice as well. I'll just copy @mratsim 's comment from another thread :
There are a lot of third-party libraries:
- eminim: https://github.com/planetis-m/eminim
- jason: https://github.com/disruptek/jason
- jsony: https://github.com/treeform/jsony
- nim-json-serialization: https://github.com/status-im/nim-json-serialization
- packedjson: https://github.com/Araq/packedjson
Deserialization usage can be seen in jsony repo: https://github.com/treeform/jsony/blob/35d9fa6/tests/bench.nim#L13-L57
Why so many? Some kind of json frenzy took Nim developers in January. Origin of the pandemic unknown, exercise caution.
I made jsony ( https://github.com/treeform/jsony ) to parse wild strange looking json. Here is how I see it: you want a Nim object, but the json is some wearied array thing of 3 elements [int, float, float]. You need a custom converter for this, its not obvious to nim or other programmers what this type is. With jsony writing a custom converter is easy, here you go:
import jsony
type DataFrame = object
count: int
start: float
stop: float
proc parseHook(s: string, i: var int, v: var DataFrame) =
var arr: array[3, float]
parseHook(s, i, arr)
v = DataFrame(count: arr[0].int, start: arr[1], stop: arr[2])
let dataframeJson = "[[110, 33.4, 45.4], [120, 34.7, 23.6]]"
echo dataframeJson.fromJson(seq[DataFrame])
You get real nim objects back:
@[
DataFrame(count:110, start:33.4, stop:45.4),
DataFrame(count:120, start:34.7, stop:23.6)
]