JSON: Difference between revisions

7,358 bytes added ,  5 months ago
m
(Pascal entry(some draft))
m (→‎{{header|Wren}}: Minor tidy)
 
(9 intermediate revisions by 8 users not shown)
Line 335:
 
Bracmat and JSON/Javascript do far from represent data in similar ways.
Bracmat has arbitrary-precision arithmetic. Floating point numbers are not a native datatype in Bracmat. (But since 2023, Bracmat has an object type, UFP, that handles floating point operations using C "double"s.)
Bracmat has no Boolean values <code>true</code> and <code>false</code> and no <code>null</code> value.
Bracmat has arrays and objects, but they are second class citizens. Most data is best represented as binary tree structures, with binary operators like the plus, comma, dot or white space sitting in the nodes and the atomic parts of the data sitting in the leaves.
Line 1,678:
end program json_fortran
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
{{libheader|YAJL}}
[https://github.com/mrozbarry/fbjson FreeBASIC JSON Parser] "JSON is simple, so the interface should also be simple" Written by Oz (alex DOT barry AT gmail DOT com) - April 22, 2010, Updated May 21, 2013
 
Sample JSON file:
<syntaxhighlight>{
"menu": { "id": "file",
"string": "File:",
"number": -3,
"boolean1":true , "boolean2" :false,"boolean3":true,
"sentence" : "the rain in spain falls mainly on the plain. This here \" is an escaped quote!",
"null": null,
"array" : [0,1,2,3]
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": "100"
},
}
}</syntaxhighlight>
 
 
<syntaxhighlight lang="vb">#include "inc/fbJSON.bas"
 
Sub printNodeChildren(Byval n As fbJSON Ptr, Byval level As Integer)
End Sub
 
Dim test As fbJSON Ptr = fbJSON_ImportFile("test1.json")
 
If test = NULL Then
Print "Unable to load json file/string!"
End 1
End If
 
Print fbJSON_ExportString(test, 1)
 
fbJSON_Delete(test)
 
Sleep</syntaxhighlight>
{{out}}
<pre>{
"menu": {
"id" : "file",
"string" : "File:",
"number" : -3,
"boolean1" : true,
"boolean2" : false,
"boolean3" : true,
"sentence" : "the rain in spain falls mainly on the plain. This here " is an escaped quote!",
"null" : null,
"array": [ 0, 1, 2, 3 ]
,
"Thumbnail": {
"Url" : "http://www.example.com/image/481989943",
"Height" : 125,
"Width" : "100"
}
 
}
 
}</pre>
 
=={{header|FunL}}==
Line 2,118 ⟶ 2,180:
'{"age":5,"name":"pojo"}'
</pre>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(var object {:a 1 :b "Hello, world!" [1 2 3] :c}
serialised (to-json object)
deserialised (from-json serialised))
 
(print "Object: " object)
(print "Serialised: " serialised)
(str "Deserialised: " deserialised)
</syntaxhighlight>
 
{{out}}
 
<pre>
Object: {:a 1, :b "Hello, world!", [1 2 3] :c}
Serialised: {":a":1,":b":"Hello, world!","[1 2 3]":":c"}
Deserialised: {":a" 1, ":b" "Hello, world!", "[1 2 3]" ":c"}
</pre>
 
Observe that JSON is incapable of lossless serialisation and deserialisation of Insitux data structures, with the recommended approach rather being [https://www.rosettacode.org/wiki/Object_serialization#Insitux <code>str</code> and <code>safe-eval</code>].
 
=={{header|J}}==
Line 3,346 ⟶ 3,430:
' "amount": 1001 ' + LineEnding +
' }, ' + LineEnding +
' "pi": 3.141161416 ' + LineEnding +
'} ';
 
Line 3,388 ⟶ 3,472:
'nothing', CreateJSON,
'object', CreateJSONObject(['product', 'unknown', 'amount', 1001]),
'pi', 3.141161416
]);
WriteLn(HandMade.FormatJson);
Line 3,749 ⟶ 3,833:
<syntaxhighlight lang="raku" line>use JSON::Tiny;
 
my $data =say from-json( '{ "foo": 1, "bar": [10, "apples"] }');
say to-json %( blue => [1,2], ocean => "water" );
 
</syntaxhighlight>
my $sample = { blue => [1,2], ocean => "water" };
{{out}}
my $json_string = to-json($sample);</syntaxhighlight>
<pre>{bar => [10 apples], foo => 1}
{ "blue" : [ 1, 2 ], "ocean" : "water" }</pre>
 
=={{header|REBOL}}==
Line 3,972 ⟶ 4,058:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var json = require('JSON::PP').new;
var data = json.decode('{"blue": [1, 2], "ocean": "water"}');
say data;
data{:ocean} = Hash.new(water => %w[fishy salty]);
say json.encode(data);</syntaxhighlight>
{{out}}
<pre>Hash.new(
'"blue'" => [1, 2],
'"ocean'" => '"water'"
)
)
{"blue":[1,2],"ocean":{"water":["fishy","salty"]}}</pre>
 
Line 4,359 ⟶ 4,445:
=={{header|TXR}}==
 
===ParsingBuilt-In===
 
TXR has built in JSON support.
 
The TXR Lisp syntax supports JSON literals, which are prefixed with <code>#J</code>.
 
<pre>1> #J{"foo" : true, [1, 2, "bar", false] : null}
#H(() ("foo" t) (#(1.0 2.0 "bar" nil) null))</pre>
 
JSON objects become hash tables, and arrays become vectors. The JSON keywords <code>true</code>, <code>false</code> and <code>null</code> become Lisp symbols <code>t</code>, <code>nil</code> and <code>null</code>.
 
The above <code>#J</code> syntax is a true hash table literal; it isn't an expression which has to be evaluated to construct the object.
 
Quasiquoting is supported over this syntax, in two usefully different ways. In quasiquoted JSON, an interpolated values are indicated not by the usual unquoting comma, but a tilde.
 
If we place the quasiquoting circumflex after the <code>#J</code>, just before the JSON syntax, then we get a form of quasiquote which interpolates values into the implied data structure. The syntax is transliterated into an invocation of a macro called <code>json</code>, which produces code to construct the object, with the dynamic values inserted into it:
 
<pre>1> (let ((str "hello"))
#J^{~str : 42})
#H(() ("hello" 42.0))</pre>
 
If the syntax is externally quasiquoted, such as by the circumflex being placed just before the <code>#J</code> or else by the JSON occurring inside a larger Lisp quasiquote, then the literal syntax itself is being quasiquoted. The result of evaluating the quasiquote isn't the object, but the syntax itself, which when evaluated again produces the object:
 
<pre>1> (let ((str "hello"))
^#J{~str : 42})
#J{"hello":42}
2> (eval *1)
#H(() ("hello" 42.0))</pre>
 
 
The <code>get-json</code> and <code>put-json</code> functions are the basic interface for reading JSON from a stream, and sending data to a stream in JSON format. Surrounding these core functions are a number of convenience functions. For instance <code>file-get-json</code> reads a JSON file and returns the data structure, and <code>tojson</code> returns an object as a JSON character string.
 
<pre>1> (file-get-json "/usr/share/iso-codes/json/iso_15924.json")
#H(() ("15924" #(#H(() ("name" "Adlam") ("alpha_4" "Adlm") ("numeric" "166"))
#H(() ("name" "Afaka") ("alpha_4" "Afak") ("numeric" "439"))
 
[ ... SNIP ... ]
 
#H(() ("name" "Code for uncoded script") ("alpha_4" "Zzzz") ("numeric" "999")))))</pre>
 
JSON is printed in a "native" formatting by default:
 
<pre>2> (put-jsonl *1)
{"15924":[{"name":"Adlam","alpha_4":"Adlm","numeric":"166"},{"name":"Afaka","alpha_4":"Afak","numeric":"439"},
{"name":"Caucasian Albanian","alpha_4":"Aghb","numeric":"239"},
{"name":"Ahom, Tai Ahom","alpha_4":"Ahom","numeric":"338"},{"name":"Arabic","alpha_4":"Arab","numeric":"160"},
 
[ ... SNIP ... ]
 
{"name":"Code for undetermined script","alpha_4":"Zyyy","numeric":"998"},
{"name":"Code for uncoded script","alpha_4":"Zzzz","numeric":"999"}]}
t</pre>
 
With the special variable <code>*print-json-format*</code> we can get the de-facto standard formatting.
 
<pre>3> (let ((*print-json-format* :standard))
(put-jsonl *1))
{
"15924" : [
{
"name" : "Adlam",
"alpha_4" : "Adlm",
"numeric" : "166"
},
{
"name" : "Afaka",
"alpha_4" : "Afak",
"numeric" : "439"
},
{
"name" : "Caucasian Albanian",
"alpha_4" : "Aghb",
"numeric" : "239"
},
 
[ ... SNIP ... ]
 
{
"name" : "Code for uncoded script",
"alpha_4" : "Zzzz",
"numeric" : "999"
}
]
}
t</pre>
 
The <code>*read-bad-json*</code> variable controls whether the parser is tolerant toward superfluous commas:
 
<pre>4> (get-json "[1, 2, 3,]")
** syntax error: read: string: errors encountered
4> (let ((*read-bad-json* t))
(get-json "[1, 2, 3,]"))
#(1.0 2.0 3.0)</pre>
 
Numbers must be floating-point in order to convert to JSON:
 
<pre>5> (put-jsonl #(1 2 3))
[** print: invalid object 1 in JSON
** during evaluation at expr-7:1 of form (put-jsonl #(1 2 3))
5> (put-jsonl #(1. 2. 3.))
[1,2,3]
t</pre>
 
This rigidity prevents errors in applications like saving some integer in JSON which unexpectedly comes back as a floating-point value, not necessarily equal to that integer.
 
===From Scratch JSON Parsing in Pattern Language===
 
The following implements the parsing half of the task. It is a parser closely based on the JSON grammar [[http://www.json.org/fatfree.html]]. This exercise shows how the TXR Pattern Language, though geared toward line-oriented, loose matching over entire documents, can nevertheless parse languages.
 
ItThis is implemented with recursive horizontal pattern matching functions, and so basically the definition resembles a grammar. Horizontal functions are a new feature in TXR, and basically allow the language to easily specify LL grammars with indefinite lookahead, not restricted to regular languages (thanks to TXR's backtracking). The numerous occurences of @\ in the code are line continuations. Horizontal functions must be written on one logical line. @\ eats the whitespace at the start of the next physical line, to allow indentation.
 
The parser translates to a nested list structure in which the types are labeled with the strings "O", "A", "N", "S" and "K". (Object, array, number, string, and keyword).
Line 4,369 ⟶ 4,560:
The largest grammar rule handles JSON string literals. The strategy is to generate a HTML string and then filter from HTML using the <code>:from_html</code> filter in TXR. For instance \uABCD is translated to <code>&amp;#xABCD;</code> and then the filter will produce the proper Unicode character. Similarly \" is translated to <code>&amp;quot;</code> and \n is translated to &#10; etc.
 
A little liberty is taken: the useless commas in JSON are treated as optional. (TXR's built-in JSON
 
Superfluous terminating commas (not generated by the JSON grammar but accepted by some other parsers) are not allowed by this parser.
Line 4,441 ⟶ 4,632:
(badsyntax . "")</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import json
 
struct User {
Line 4,484 ⟶ 4,675:
=={{header|Wren}}==
{{libheader|Wren-json}}
<syntaxhighlight lang="ecmascriptwren">import "/json" for JSON
 
var s = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"
9,485

edits