Jump to content

JSON: Difference between revisions

2,057 bytes added ,  9 years ago
Add solution for Lua using luajson
(→‎{{header|Bracmat}}: Changed to full length JSON output, so readers can copy/paste to jsonlint)
(Add solution for Lua using luajson)
Line 1,461:
ExportString[data, "JSON"]
</lang>
 
=={{header|Lua}}==
 
Using the [https://github.com/harningt/luajson luajsson] library:
 
<lang lua>local json = require("json")
 
local json_data = [=[[
42,
3.14159,
[ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ],
{ "H": 1, "He": 2, "X": null, "Li": 3 },
null,
true,
false
]]=]
 
print("Original JSON: " .. json_data)
local data = json.decode(json_data)
json.util.printValue(data, 'Lua')
print("JSON re-encoded: " .. json.encode(data))
 
local data = {
42,
3.14159,
{
2, 4, 8, 16, 32, 64,
"apples",
"bananas",
"cherries"
},
{
H = 1,
He = 2,
X = json.util.null(),
Li = 3
},
json.util.null(),
true,
false
}
 
print("JSON from new Lua data: " .. json.encode(data))</lang>
 
Since in Lua <code>nil</code> signifies an ''undefined'' value, i.e. a variable or table entry with a <code>nil</code> value is undistinguishable from an undefined variable or non-existing table entry, a <code>null</code> value in JSON notation is decoded to a special function value, which ensures that it can be re-encoded properly to <code>null</code> again. To manually insert a <code>null</code> value in the JSON output, use the <code>json.util.null</code> function.
 
'''Output:'''
 
Original JSON: [
42,
3.14159,
[ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ],
{ "H": 1, "He": 2, "X": null, "Li": 3 },
null,
true,
false
]
Lua= {
1=42
2=3.14159
3= {
1=2
2=4
3=8
4=16
5=32
6=64
7=[[apples]]
8=[[bananas]]
9=[[cherries]]
4= {
Li=3
He=2
H=1
X=function: 0x8f6f00
5=function: 0x8f6f00
6=true
7=false
JSON re-encoded: [42,3.14159,[2,4,8,16,32,64,"apples","bananas","cherries"],{"Li":3,"He":2,"H":1,"X":null},null,true,false]
JSON from new Lua data: [42,3.14159,[2,4,8,16,32,64,"apples","bananas","cherries"],{"Li":3,"He":2,"H":1,"X":null},null,true,false]
 
=={{header|MATLAB}} / {{header|Octave}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.