Am 13.07.2019 um 10:57 schrieb Artur Tarassow:
Am 12.07.19 um 19:28 schrieb Sven Schreiber:
> Am 12.07.2019 um 18:01 schrieb Artur Tarassow:
>> Currently, gretl can read-in json-files and converts them into a
>> bundle or array of bundles.
>
> Right, and perhaps json could therefore be the format of choice for the
> direction Python -> gretl. Do you think you could write a Python
> function that produces something that's readable with gretl's jsongetb?
I guess this is not necessary as the json.dumps() function of the Python
package "json" already converts a dictionary into json format which is
fully readable by gretl's jsongetb():
https://www.w3schools.com/python/python_json.asp
Well, not so fast. Gretl's doc for jsongetb says: "JSON arrays become
gretl arrays, each of which holds either strings or bundles"
And indeed, consider the following:
<hansl>
string j = sprintf("{\"vec\": [1, 2, 3]}")
eval jsongetb(j).vec
</hansl>
which gives:
Array of strings, length 3
[1] "1"
[2] "2"
[3] "3"
So reading in data arrays would seem to need some adjustment on the
gretl side.
>> But there is no way function for writing a bundle's
underlying
>> xml-structure in json-format.
> I think it would be doable to write a hansl function for this which
> could go into the "extra" package.
Yes, this shouldn't be too hard to write given that xml is structured. I
am currently too busy with other projects but can I put it on my list of
todos.
Here's an attempt which seems to work for me so far:
<hansl>
function string gbundle2json(bundle b)
strings keys = getkeys(b)
string out = "{"
loop k=1..nelem(keys) -q
string key = keys[k]
# print the key
out ~= sprintf("\n\"%s\": ", key)
# print the value
string typ = typestr(typeof(b["@key"]))
if typ == "string"
out ~= sprintf("\"%s\"", b[key])
elif typ == "scalar"
out ~= sprintf("%g", b[key])
elif typ == "series" || typ == "matrix" # (series as vector)
matrix m = (typ == "series") ? {b[key]} : b[key]
# matrix and vector always two-dim
out ~= "["
loop r=1..rows(m) -q
string stemp = "["~ strstrip( sprintf("%14.10f", m[r,]) )
~"]"
out ~= regsub(stemp, "\s+", ",") # replace (multiple) blanks
out ~= (r < rows(m)) ? sprintf(",\n") : sprintf("]")
endloop
else
printf "Warning, type %s not supported, skipping", typ
endif
out ~= (k < nelem(keys)) ? "," : sprintf("\n}")
endloop
return out
end function
## test
bundle bin = defbundle("a","heyho", "b",$pi,
"mm",mnormal(5,2),
"m2",ones(1,3))
string js = gbundle2json(bin)
print js
</hansl>
cheers
sven