31 lines
1.5 KiB
Plaintext
31 lines
1.5 KiB
Plaintext
do -- JSON encode/decode - translation of the Phix sample, using Pluto's standard json module
|
|
|
|
local json = require( "json" )
|
|
|
|
print( "roundtrip (10 examples):" )
|
|
|
|
local json_strings <const> = { '{"this":"that","age":{"this":"that","age":29}}'
|
|
, '1'
|
|
, '"hello"'
|
|
, 'null'
|
|
, '[12]'
|
|
, '[null,12]'
|
|
, '[]'
|
|
, '{"this":"that","age":29}'
|
|
, '{}'
|
|
, '[null,[null,12]]'
|
|
}
|
|
|
|
for i = 1, #json_strings do
|
|
local s <const> = json_strings[ i ]
|
|
local j <const> = json.decode( s, json.withnull | json.withorder ) -- parse the string into a table
|
|
-- preserving nulls and element order
|
|
local r <const> = json.encode( j ) -- turn j back into a JSON string
|
|
local v <const> = dumpvar( j ):gsub( "\n", "" ):gsub( "\t", "" ) -- the table as a readable string
|
|
local sp <const> = " "
|
|
io.write( " ", s, if #s >= #sp then "\n "..sp else sp:sub( 1, #sp - #s ) end )
|
|
io.write( "-> ", if #v > 50 then v:sub( 1, 47 ).."..." else v end, "\n" )
|
|
io.write( if s == r then "-> " else "** " end, r, "\n\n" )
|
|
end
|
|
end
|