Am 28.02.2019 um 08:43 schrieb Riccardo (Jack) Lucchetti:
On Thu, 28 Feb 2019, Sven Schreiber wrote:
> I'm still talking about stuff I don't fully understand,
but maybe we
> should have a hansl function that writes out the contents of a bundle
> (or let's say, a well-defined subset of possible contents) as a json
> string or file. That would complement the existing native jsongetb
> function.
> Perhaps such a thing could go into the extra.gfn add-on.
Hm, that'd be quite complex to write, but it's a good idea.
He, is that a challenge? ;-)
As I said, my json knowledge is limited to the Wikipedia entry, but does
the following prototype give a valid json document?
cheers
sven
<hansl>
function string matrowcommasep(matrix m)
# m should be a row vector
m = vec(m)'
string mp = strstrip( sprintf("%20.10g", m) )
# remove multiple blanks
# (this could be done cleverly with regsub)
loop while instring(mp, " ") --quiet # two blanks
mp = strsub(mp, " ", " ") # one blank
endloop
# comma as separator
return strsub(mp, " ", ",")
end function
function string bundle2json(bundle b)
string out = sprintf("{\n")
strings keys = getkeys(b)
loop i = 1..nelem(keys) --quiet
string key = keys[i]
if typeof(b[key]) == 1 # scalar
out ~= sprintf("\"%s\": %g,\n", key, b[key])
elif typeof(b[key]) == 3 # matrix
out ~= sprintf("\"%s\": [", key)
loop r = 1..rows(b[key]) --quiet
out ~= sprintf("\n[") ~ matrowcommasep(b[key][r,]) ~ "],"
endloop
# strip the trailing comma and close array
out = out[1: strlen(out)-1] ~ sprintf("\n],\n")
else
funcerr "type not implemented"
endif
endloop
# replace trailing comma and newline
return out[1: strlen(out) - 2] ~ sprintf("\n}")
end function
#### test code
bundle b = defbundle("mymat",I(2), "myscal",3)
eval bundle2json(b)
</hansl>