JSON: Difference between revisions

22,619 bytes added ,  5 months ago
m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(37 intermediate revisions by 23 users not shown)
Line 5:
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
 
=={{header|11l}}==
<syntaxhighlight lang="11l">T.serializable Person
String firstName, lastName
Int age
T PhoneNumber
String ntype
String number
[PhoneNumber] phoneNumbers
[String] children
 
Person p
 
json:to_object(‘
{
"firstName": "John",
"lastName": "Smith",
"age": 27,
"phoneNumbers": [
{
"ntype": "home",
"number": "212 555-1234"
},
{
"ntype": "office",
"number": "646 555-4567"
}
],
"children": ["Mary", "Kate"]
}’, &p)
 
p.phoneNumbers.pop(0)
p.children.append(‘Alex’)
 
print(json:from_object(p))</syntaxhighlight>
 
{{out}}
<pre>
{
"age": 27,
"children": [
"Mary",
"Kate",
"Alex"
],
"firstName": "John",
"lastName": "Smith",
"phoneNumbers": [
{
"ntype": "office",
"number": "646 555-4567"
}
]
}
</pre>
 
=={{header|8th}}==
Line 25 ⟶ 80:
=={{header|Ada}}==
=== Alternative using GNATCOLL ===
<langsyntaxhighlight lang="ada">
with Ada.Text_IO;
with GNATCOLL.JSON;
Line 67 ⟶ 122:
Put_Line (Penguin.Write);
end JSON_Test;
</syntaxhighlight>
</lang>
 
{{out}}
Line 77 ⟶ 132:
=== Alternative using Matreshka ===
 
<langsyntaxhighlight lang="ada">
with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO;
with League.JSON.Arrays; use League.JSON.Arrays;
Line 119 ⟶ 174:
Put_Line (To_JSON_Document (Penguin).To_JSON.To_Wide_Wide_String);
end Main;
</syntaxhighlight>
</lang>
 
{{out}}
Line 129 ⟶ 184:
=={{header|AntLang}}==
JSON parser (maybe failes with "invalid JSON" error)
<syntaxhighlight lang="antlang">
<lang AntLang>
json:{[data]catch[eval[,|{[y]catch[{":" = "="; "[" = "<"; "]" = ">"; "," = ";"}[y];{x};{[]y}]}'("""("(\\.|[^\\"])*"|\-?[0-9]+(\.[0-9]+)?|\{|\}|\[|\]|\:|\,)"""~data)["strings"]];{x};{error["Invalid JSON"]}]}
</syntaxhighlight>
</lang>
 
=={{header|ANTLR}}==
Line 144 ⟶ 199:
 
===Java===
<langsyntaxhighlight lang="java">
// Parse JSON
//
Line 168 ⟶ 223:
| array;
array : '[' {System.out.println(Indent + "Array"); Indent += " ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};
</syntaxhighlight>
</lang>
Produces:
<pre>
Line 207 ⟶ 262:
=={{header|Apex}}==
JSON serialization and deserialization is built in
<langsyntaxhighlight lang="apex">class TestClass{
String foo {get;set;}
Integer bar {get;set;}
Line 221 ⟶ 276:
//"testObj.foo == deserializedObject.foo" is true
//"testObj.bar == deserializedObject.bar" is true
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print read.json {{ "foo": 1, "bar": [10, "apples"] }}
<lang arturo>// set some json string
json: "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
 
object: #[
// parsing json string to object
print "JSON:"
inspect [parseJson json]
 
// set some object
object: #{
name: "john"
surname: "doe"
address: #{[
number: 10
street: "unknown"
country: "Spain"
]
}
married: false
]
}
 
// generateprint write.json string from ø object</syntaxhighlight>
print "OBJECT:"
print [generateJson object]
</lang>
 
{{out}}
 
<pre>JSON[foo:1 bar:[10 apples]]
#{
bar : #(
10
"apples"
)
foo : 1
}
OBJECT:
{
"name": "john",
Line 276 ⟶ 314:
A full roundtrip from JSON file over a Bracmat internal representation back to a JSON file looks like this:
 
<langsyntaxhighlight lang="bracmat">put$(jsn$(get$("input.json",JSN)),"output.JSN,NEW)</langsyntaxhighlight>
 
Let us split this into separate steps.
Line 282 ⟶ 320:
To read a JSON file "myfile.json", use
 
<langsyntaxhighlight lang="bracmat">get$("myfile.json",JSN)</langsyntaxhighlight>
 
If the JSON data, e.g, an array, has to be read from a string value, use the <code>MEM</code> option on the <code>get</code> function, like this:
 
<langsyntaxhighlight lang="bracmat">get$("[1,2,3]",JSN,MEM)</langsyntaxhighlight>
 
To convert the corresponding Bracmat data structure <code>(,1 2 3)</code> back to a JSON string, use
 
<syntaxhighlight lang ="bracmat">jsn$(,1 2 3)</langsyntaxhighlight>
 
To write a JSON string <code>"[1,2,3]"</code> to a file "array.json", use
 
<langsyntaxhighlight lang="bracmat">put$("[1,2,3]","array.json",NEW)</langsyntaxhighlight>
 
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 344 ⟶ 382:
Here is a full round trip of the following JSON data, which is assumed to be stored in a file "rosetta.json".
The employed code is:
<langsyntaxhighlight lang="bracmat">
( get$("rosetta.json",JSN):?json
& lst$(json,"json.bra",NEW)
& put$(jsn$!json,"rosetta-roundtrip.json",NEW)
)</langsyntaxhighlight>
 
rosetta.json:
Line 525 ⟶ 563:
Reads a snippet of JSON into [https://github.com/lloyd/yajl YAJL's] tree format, then walks the tree to print it back out again. The tree contains numbers both in an unparsed, string form, and also converted to long long or double when possible. The example below demonstrates both ways of dealing with numbers.
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 644 ⟶ 682:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 677 ⟶ 715:
This uses the [http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=VS.90).aspx JavaScriptSerializer] class which was shipped with .NET 3.5.
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
Line 699 ⟶ 737:
Console.WriteLine(array[1]);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 705 ⟶ 743:
{{libheader|U++}}
 
<langsyntaxhighlight lang="cpp">#include "Core/Core.h"
 
using namespace Upp;
Line 719 ⟶ 757:
Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}
</syntaxhighlight>
</lang>
 
C++11 {{libheader|nlohmann&#58;&#58;json}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iomanip> // std::setw
#include <sstream>
Line 787 ⟶ 825:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Caché ObjectScript}}==
 
<langsyntaxhighlight lang="cos">
Class Sample.JSON [ Abstract ]
{
Line 802 ⟶ 840:
 
}
</syntaxhighlight>
</lang>
{{out|Examples}}
<pre>
Line 854 ⟶ 892:
=={{header|Clojure}}==
Library: [https://github.com/clojure/data.json data.json]
<langsyntaxhighlight lang="clojure">(use 'clojure.data.json)
 
; Load as Clojure data structures and bind the resulting structure to 'json-map'.
Line 863 ⟶ 901:
 
; Pretty-print the Clojure representation of JSON. We've come full circle.
(pprint-json json-map)</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
sample =
blue: [1, 2]
Line 876 ⟶ 914:
console.log json_string
console.log json_obj
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
<syntaxhighlight lang="cfm">
<!--- Create sample JSON structure --->
<cfset json = {
string: "Hello",
number: 42,
arrayOfNumbers: [1, 2, 3, 4],
arrayOfStrings: ["One", "Two", "Three", "Four"],
arrayOfAnything: [1, "One", [1, "One"], { one: 1 }],
object: {
key: "value"
}
} />
 
<!--- Convert to JSON string --->
<cfset jsonSerialized = serializeJSON(json) />
<!--- Convert back to ColdFusion --->
<cfset jsonDeserialized = deserializeJSON(jsonSerialized) />
 
<!--- Output examples --->
<cfdump var="#jsonSerialized#" />
<cfdump var="#jsonDeserialized#" />
</syntaxhighlight>
 
=={{header|Common Lisp}}==
Library: [https://github.com/hankhero/cl-json cl-json]
<langsyntaxhighlight lang="lisp">
(ql:quickload '("cl-json"))
 
Line 891 ⟶ 953:
(json:decode-json s)))
 
</syntaxhighlight>
</lang>
 
<pre>To load "cl-json":
Line 903 ⟶ 965:
 
=={{header|Crystal}}==
Before 1.0.0:
<lang Ruby>
<syntaxhighlight lang="ruby">
require "json"
require "json_mapping"
 
class Foo
Line 918 ⟶ 981:
puts(foo.to_json)
end
</syntaxhighlight>
</lang>
 
After 1.0.0:
<syntaxhighlight lang="ruby">
require "json"
 
class Foo
include JSON::Serializable
property num : Int64
property array : Array(String)
end
 
def json
foo = Foo.from_json(%({"num": 1, "array": ["a", "b"]}))
puts("#{foo.num} #{foo.array}")
puts(foo.to_json)
end
</syntaxhighlight>
 
Output:
<lang Bash>
<pre>1 ["a", "b"]
{"num":1,"array":["a","b"]}</pre>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.json;
void main() {
auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
writeln(toJSON(&j));
}</langsyntaxhighlight>
<pre>{"foo":1,"bar":[10,"apples"]}</pre>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="javascript">import 'dart:convert' show jsonDecode, jsonEncode;
 
main(){
Line 965 ⟶ 1,045:
assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 975 ⟶ 1,055:
 
{{trans|JavaScript}}
<langsyntaxhighlight lang="javascript">import 'dart:convert';
 
main(){
Line 984 ⟶ 1,064:
var json_string = jsonEncode(sample);
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program JsonTest;
 
Line 1,043 ⟶ 1,123:
Readln;
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,054 ⟶ 1,134:
=={{header|EchoLisp}}==
The '''json''' library allows to import/export basic JSON types (string ,numbers, arrays) and to translate EchoLisp objects (lists, dates, ..) from/to JSON objects and types. See reference documentation [[http://www.echolalie.org/echolisp/help.html#export-json]].
<langsyntaxhighlight lang="lisp">
;; JSON standard types : strings, numbers, and arrays (vectors)
(export-json #(6 7 8 9)) → "[6,7,8,9]"
Line 1,090 ⟶ 1,170:
→ # (simon 🎩)
 
</syntaxhighlight>
</lang>
 
 
Line 1,097 ⟶ 1,177:
 
Structures used both to construct and to parse JSON strings:
<langsyntaxhighlight EGLlang="egl">record familyMember
person person;
relationships relationship[]?;
Line 1,111 ⟶ 1,191:
relationshipType string;
id int;
end</langsyntaxhighlight>
 
Construct JSON string:
<langsyntaxhighlight EGLlang="egl">people Person[]; // Array of people
people.appendElement(new Person { firstName = "Frederick", lastName = "Flintstone", age = 35} );
Line 1,135 ⟶ 1,215:
 
// Show JSON string
SysLib.writeStdout(jsonString);</langsyntaxhighlight>
 
{{out|Raw Output}}
Line 1,170 ⟶ 1,250:
 
Parse JSON:
<langsyntaxhighlight EGLlang="egl">// Convert JSON string into dictionary of family members
family Dictionary;
jsonLib.convertFromJSON(jsonString, family);
Line 1,194 ⟶ 1,274:
end
 
end</langsyntaxhighlight>
 
{{out}}
Line 1,223 ⟶ 1,303:
The examples above illustrate that it is possible to perform manual conversions to and from a JSON format but in EGL it is much more common for the programming language to handle these conversion automatically as a natural part of service invocations. Below is an example of a function definition designed to consume the Google Maps Geocoding service. The results are returned in a JSON format and parsed by EGL into records that mirror the structure of the reply.
 
<langsyntaxhighlight EGLlang="egl">// Service function definition
function geocode(address String) returns (GoogleGeocoding) {
@Resource{uri = "binding:GoogleGeocodingBinding"},
Line 1,237 ⟶ 1,317:
SysLib.writeStdout(result.results[1].geometry.location.lat);
SysLib.writeStdout(result.results[1].geometry.location.lng);
end</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x
<langsyntaxhighlight lang="elena">import extensions;
import extensions'dynamic;
Line 1,252 ⟶ 1,332:
console.printLine("json.foo=",o.foo);
console.printLine("json.bar=",o.bar)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,260 ⟶ 1,340:
 
=={{header|Emacs Lisp}}==
A JSON encoder and decoder is in package json, so load it first:
<lang Lisp>(require 'json)</lang>
===Decoding===
<lang Lisp>(setq example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(json-read-from-string example)
</lang>
{{out}}
<lang Lisp>((foo . "bar")
(baz .
[1 2 3]))</lang>
===Decoding, representing data as property lists===
<lang Lisp>(let ((json-object-type 'plist))
(json-read-from-string))</lang>
{{out}}
<lang Lisp>(:foo "bar" :baz
[1 2 3])</lang>
===Decoding, representing data as hash table===
<lang Lisp>(let ((json-object-type 'hash-table))
(json-read-from-string example))</lang>
{{out}}
<pre>#<hash-table equal 2/65 0x1563c39805fb></pre>
 
{{libheader|Jansson}}
===Encoding===
 
<Lang Lisp>(json-encode example-object)</Lang>
Emacs 27.1 offers native JSON processing using the Jansson library.
 
<syntaxhighlight lang="lisp">(require 'cl-lib)
 
(cl-assert (fboundp 'json-parse-string))
(cl-assert (fboundp 'json-serialize))
 
(defvar example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(defvar example-object '((foo . "bar") (baz . [1 2 3])))
 
;; decoding
(json-parse-string example) ;=> #s(hash-table [...]))
;; using json.el-style options
(json-parse-string example :object-type 'alist :null-object nil :false-object :json-false)
;;=> ((foo . "bar") (baz . [1 2 3]))
;; using plists for objects
(json-parse-string example :object-type 'plist) ;=> (:foo "bar" :baz [1 2 3])
 
;; encoding
(json-serialize example-object) ;=> "{\"foo\":\"bar\",\"baz\":[1,2,3]}"</syntaxhighlight>
 
{{libheader|json.el}}
 
<syntaxhighlight lang="lisp">(require 'json)
 
(defvar example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(defvar example-object '((foo . "bar") (baz . [1 2 3])))
 
;; decoding
(json-read-from-string example) ;=> ((foo . "bar") (baz . [1 2 3]))
;; using plists for objects
(let ((json-object-type 'plist))
(json-read-from-string)) ;=> (:foo "bar" :baz [1 2 3])
;; using hash tables for objects
(let ((json-object-type 'hash-table))
(json-read-from-string example)) ;=> #<hash-table equal 2/65 0x1563c39805fb>
 
;; encoding
(json-encode example-object) ;=> "{\"foo\":\"bar\",\"baz\":[1,2,3]}"
;; pretty-printing
(let ((json-encoding-pretty-print t))
(message "%s" (json-encode example-object)))</syntaxhighlight>
 
{{out}}
 
<pre>"{\"list\":{\"cons\":[[\"quote\",\"x\"],2],\"cons\":[[\"quote\",\"y\"],\"a string\"]}}"</pre>
{
===Encoding, pretty printing output===
"foo": "bar",
<lang Lisp>(let ((json-encoding-pretty-print t))
"baz": [
(json-encode example-object))</lang>
1,
{{out}}
2,
<pre>
3
"{
\"list\": {]
}
\"cons\": [
[
\"quote\",
\"x\"
],
2
],
\"cons\": [
[
\"quote\",
\"y\"
],
\"a string\"
]
}
}"
</pre>
===Encoding, with options===
<lang Lisp>(let* ((json-encoding-pretty-print t)
(json-object-type 'alist)
(json-array-type 'vector)
(json-key-type 'symbol)
(vec (make-vector 3 "element")))
(aset vec 1 "second")
(aset vec 2 -3)
(json-encode (list (cons 'x 2)
(cons 'y "a string")
(cons 'z vec))))</lang>
{{out}}
<pre>"{
\"x\": 2,
\"y\": \"a string\",
\"z\": [
\"element\",
\"second\",
-3
]
}"</pre>
 
=={{header|Erlang}}==
Use the JSON library for Erlang (mochijson) from [https://github.com/mochi/mochiweb/blob/master/src/mochijson.erl mochiweb]. The JSON code is extracted from [http://en.wikipedia.org/wiki/JSON#JSON_example wikipedia]
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(json).
-export([main/0]).
Line 1,376 ⟶ 1,441:
io:format("JSON -> Erlang\n~p\n",[mochijson:decode(JSON)]),
io:format("Erlang -> JSON\n~s\n",[mochijson:encode(Erlang)]).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,398 ⟶ 1,463:
 
1. Using Json.Net
<langsyntaxhighlight lang="fsharp">
open Newtonsoft.Json
type Person = {ID: int; Name:string}
Line 1,408 ⟶ 1,473:
let xs1 = JsonConvert.DeserializeObject<Person list>(json)
xs1 |> List.iter(fun x -> printfn "%i %s" x.ID x.Name)
</syntaxhighlight>
</lang>
 
Print:
<langsyntaxhighlight lang="fsharp">[{"ID":1,"Name":"First"},{"ID":2,"Name":"Second"}]
1 First
2 Second
</syntaxhighlight>
</lang>
2. Using FSharp.Data
<langsyntaxhighlight lang="fsharp">open FSharp.Data
open FSharp.Data.JsonExtensions
 
Line 1,429 ⟶ 1,494:
| JsonValue.Array(x) -> x |> Array.map(fun x -> {ID = System.Int32.Parse(string x?ID); Name = (string x?Name)})
| _ -> failwith "fail json"
|> Array.iter(fun x -> printfn "%i %s" x.ID x.Name)</langsyntaxhighlight>
Print:
<langsyntaxhighlight lang="fsharp">[
{
"ID": 1,
Line 1,443 ⟶ 1,508:
1 "First"
2 "Second"
</syntaxhighlight>
</lang>
3. Alternative way of parsing: JsonProvider
<langsyntaxhighlight lang="fsharp">open FSharp.Data
type Person = {ID: int; Name:string}
type People = JsonProvider<""" [{"ID":1,"Name":"First"},{"ID":2,"Name":"Second"}] """>
Line 1,451 ⟶ 1,516:
People.GetSamples()
|> Array.map(fun x -> {ID = x.Id; Name = x.Name} )
|> Array.iter(fun x -> printfn "%i %s" x.ID x.Name) </langsyntaxhighlight>
Print:<langsyntaxhighlight lang="fsharp">
1 First
2 Second
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">
<lang Factor>
USING: json.writer json.reader ;
 
Line 1,469 ⟶ 1,534:
! Create a new data structure and serialize into JSON
{ { "blue" { "ocean" "water" } } >json
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
using util
 
Line 1,492 ⟶ 1,557:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,501 ⟶ 1,566:
"ocean":{"water":["cold","blue"]}}
</pre>
 
=={{header|Forth}}==
Forth has no built-in high level data structures such as arrays,
strings, and objects. Nor is there a standardized Forth library to build
and use such structures. But there are many different Forth libraries,
written by individuals, available though finding them is not always easy and the syntax and behavior is different for each.
The library code used below can be found here:
https://github.com/DouglasBHoffman/FMS2
 
Load a JSON Forth string into a json data structure and print it.
<pre>
s\" {\"value\":10,\"flag\":false,\"array\":[1,2,3]}" $>json value j
j :.
</pre>
Prints a JSON as follows:
{
"value": 10,
"flag": false,
"array": [ 1, 2, 3]
}
 
Create a new Json data structure (here a Json pair), and insert it into the previous Json object. Print it again.
<pre>
j{ "another":"esc\"ap\u20ACed" }j j :add j :.
</pre>
Prints the modified JSON:
 
{
"value": 10,
"flag": false,
"array": [ 1, 2, 3],
"another": "esc"ap€ed"
}
 
 
Serialize the JSON object into a string. Print the string.
<pre>
j json>$ :.
</pre>
{"value":10,"flag":false,"array":[1,2,3],"another":"esc\"ap\u20ACed"}
 
=={{header|Fortran}}==
Line 1,523 ⟶ 1,628:
</pre>
 
<langsyntaxhighlight lang="fortran">
program json_fortran
use json_module
Line 1,572 ⟶ 1,677:
 
end program json_fortran
</syntaxhighlight>
</lang>
 
=={{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 1,579 ⟶ 1,746:
Built-in <code>println()</code> also produces JSON conformant output.
This method only uses built-in functions but is comparatively slow.
<langsyntaxhighlight lang="funl">println( eval('{ "foo": 1, "bar": [10, "apples"] }') )</langsyntaxhighlight>
 
Using module <code>json</code> gives better performance and also pretty prints the JSON output.
<langsyntaxhighlight lang="funl">import json.*
 
DefaultJSONWriter.write( JSONReader({'ints', 'bigInts'}).fromString('{ "foo": 1, "bar": [10, "apples"] }') )</langsyntaxhighlight>
 
{{out}}
Line 1,597 ⟶ 1,764:
}
</pre>
 
 
 
 
=={{header|FutureBasic}}==
FB has dedicated JSON functions making easy to serialize objects as JSON and to convert JSON to objects.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn DoIt
ErrorRef err = NULL
CFStringRef jsonString = @"{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
CFDataRef strData = fn StringData( jsonString, NSUTF8StringEncoding )
CFTypeRef jsonObj = fn JSONSerializationJSONObjectWithData( strData, NULL, @err )
if err then NSLog( @"%@", fn ErrorLocalizedDescription( err ) )
NSLog( @"%@\n", jsonObj )
CfDictionaryRef dict = @{ @"blue": @[@1, @2], @"ocean": @"water"}
CFDataRef jsonData = fn JSONSerializationDataWithJSONObject( dict, 0, @err )
if err then NSLog( @"%@", fn ErrorLocalizedDescription( err ) )
CFStringRef jsonString2 = fn StringWithData( jsonData, NSUTF8StringEncoding )
NSLog( @"%@\n", jsonString2 )
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
{
bar = (
10,
apples
);
foo = 1;
}
 
{"blue":[1,2],"ocean":"water"}
</pre>
 
 
 
 
 
=={{header|Go}}==
Example below shows simple correspondence between JSON objects and Go maps, and shows that you don't have to know anything about the structure of the JSON data to read it in.
<langsyntaxhighlight lang="go">package main
 
import "encoding/json"
Line 1,624 ⟶ 1,836:
fmt.Println(err)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,631 ⟶ 1,843:
</pre>
Example below demonstrates more typical case where you have an expected correspondence between JSON data and some composite data types in your program, and shows how the correspondence doesn't have to be exact.
<langsyntaxhighlight lang="go">package main
 
import "encoding/json"
Line 1,689 ⟶ 1,901:
fmt.Println(string(jData))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,715 ⟶ 1,927:
]
</pre>
 
 
 
 
=={{header|Gosu}}==
Gosu consumes JSON as a Dynamic type via this core API:
<langsyntaxhighlight lang="javascript">
gw.lang.reflect.json.Json#fromJson( String json ) : javax.script.Bindings
</syntaxhighlight>
</lang>
As the signature of the method suggests, you pass in a JSON string and receive standard script Bindings in return. Bindings is basically a map mirroring the tree structure of the JSON object. Internally Gosu supports any Bindings instance as a Dynamic Expando object. Essentially this means you can directly cast any Bindings instance to Dynamic and treat it as an Expando.
 
Line 1,726 ⟶ 1,941:
 
Sample Person JSON (from http://gosu-lang.github.io/data/person.json):
<langsyntaxhighlight lang="javascript">{
"Name": "Dickson Yamada",
"Age": 39,
Line 1,746 ⟶ 1,961:
]
}
</syntaxhighlight>
</lang>
And the dynamic Gosu code to access it:
<langsyntaxhighlight lang="javascript">
var personUrl = new URL( "http://gosu-lang.github.io/data/person.json" )
var person: Dynamic = personUrl.JsonContent
print( person.Name )
</syntaxhighlight>
</lang>
Notice the JsonContent property on URL:
<langsyntaxhighlight lang="javascript">
personUrl.JsonContent
</syntaxhighlight>
</lang>
This is a convenient enhancement property Gosu provides for Java’s URL class. It does all the work to get the JSON text and calls the new Json#fromJson() method for you. It also declares the Dynamic type for you as its return type, so the declared Dynamic type on the person var is unnecessary; it’s there to clearly demonstrate that the person var is indeed Dynamic.
 
Line 1,762 ⟶ 1,977:
 
Here’s how we make the previous example work statically:
<langsyntaxhighlight lang="javascript">
print( person.toStructure( "Person", false ) )
</syntaxhighlight>
</lang>
Gosu enhances Bindings with the method, toStructure( name: String, mutable: boolean ). Note the resulting structure is optionally mutable via the mutable argument. This method generates the complete nesting of types plus convenient factory methods:
<langsyntaxhighlight lang="javascript">
structure Person {
static function fromJson( jsonText: String ): Person {
Line 1,795 ⟶ 2,010:
}
}
</syntaxhighlight>
</lang>
The Person structure reflects the JSON object’s implied type nesting. You can do whatever you like with this type. You can embed it as an inner structure in an existing class or make a top-level type. In any case all the types in the JSON object are uniquely preserved in one structure. Use it like this:
<langsyntaxhighlight lang="javascript">
var person = Person.fromJsonUrl( personUrl )
print( person.Name )
print( person.Address.City )
print( person.Hobby[0].Name )
</syntaxhighlight>
</lang>
All statically verified and fully code completion friendly!
Other features:
<langsyntaxhighlight lang="javascript">
print( person.toJson() ) // toJson() generates the Expando bindings to a JSON string
print( person.toGosu() ) // toGosu() generates any Bindings instance to a Gosu Expando initializer string
print( person.toXml() ) // toXml() generates any Bindings instance to standard XML
</syntaxhighlight>
</lang>
And similar to JavaScript, you can directly evaluate a Gosu Expando initializer string:
<langsyntaxhighlight lang="javascript">
var clone = eval( person.toGosu() )
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
Line 1,821 ⟶ 2,036:
Note that JsonSlurper accepts an extra comma such as [1,2,3,]. This is an extension to the [[http://www.json.org/fatfree.html JSON grammar]].
 
<langsyntaxhighlight lang="groovy">def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText('''
{
Line 1,833 ⟶ 2,048:
]
}
''')</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">result.each { println it.key; it.value.each {person -> println person} }
 
assert result.people[0].name == [family:'Flintstone', given:'Frederick']
Line 1,843 ⟶ 2,058:
assert result.people[3].name == [family:'Rubble', given:'Elisabeth']
assert Eval.x(result, 'x.' + result.people[2].relationships.wife + '.name') == [family:'Rubble', given:'Elisabeth']
assert Eval.x(result, 'x.' + result.people[1].relationships.husband + '.name') == [family:'Flintstone', given:'Frederick']</langsyntaxhighlight>
 
{{out}}
Line 1,855 ⟶ 2,070:
 
=={{header|Halon}}==
<langsyntaxhighlight lang="halon">$data = json_decode(''{ "foo": 1, "bar": [10, "apples"] }'');
 
$sample = ["blue" => [1, 2], "ocean" => "water"];
$jsonstring = json_encode($sample, ["pretty_print" => true]);</langsyntaxhighlight>
 
=={{header|Harbour}}==
Parse JSON string into the ''arr'' variable:
<langsyntaxhighlight lang="visualfoxpro">LOCAL arr
hb_jsonDecode( '[101,[26,"Test1"],18,false]', @arr )</langsyntaxhighlight>
{{out}} the JSON representation of an array ''arr'':
<langsyntaxhighlight lang="visualfoxpro">LOCAL arr := { 101, { 18, "Test1" }, 18, .F. }
? hb_jsonEncode( arr )
// The output is:
// [101,[26,"Test1"],18,false]</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,874 ⟶ 2,089:
Uses the Aeson library from hackage (http://hackage.haskell.org/package/aeson).
 
<syntaxhighlight lang="haskell">
<lang Haskell>
{-# LANGUAGE OverloadedStrings #-}
 
Line 1,900 ⟶ 2,115:
Right v | otherwise -> print v
 
</syntaxhighlight>
</lang>
 
An example using Aeson and TemplateHaskell. Note that it can handle the absence of keys.
<langsyntaxhighlight lang="haskell">
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
import Data.Aeson
Line 1,920 ⟶ 2,135:
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)
</syntaxhighlight>
</lang>
 
An example using Aeson and GHC.Generics. Note that it can handle the absence of keys.
<langsyntaxhighlight lang="haskell">
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import Data.Aeson
Line 1,941 ⟶ 2,156:
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)
</syntaxhighlight>
</lang>
 
=={{header|Hoon}}==
<langsyntaxhighlight Hoonlang="hoon">:- %say
|= [^ [in=@tas ~] ~]
:- %noun
Line 1,958 ⟶ 2,173:
=. age.o +(age.o) :: increment its age...
%: crip %: pojo :: pretty-print result
(jobe [%name s/name.o] [%age n/(crip <age.o>)] ~) :: convert back to json</langsyntaxhighlight>
 
Usage: Put code in gen/json.hoon
Line 1,965 ⟶ 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 1,970 ⟶ 2,207:
Here is a minimal implementation based on [http://www.jsoftware.com/pipermail/chat/2007-April/000462.html an old email message].
 
<langsyntaxhighlight lang="j">NB. character classes:
NB. 0: whitespace
NB. 1: "
Line 2,019 ⟶ 2,256:
jsonSer0=: '"', jsonEsc@:":, '"'"_
jsonEsc=: rplc&(<;._1' \ \\ " \"')
jsonSerialize=:jsonSer0`jsonSer2@.(*@L.)</langsyntaxhighlight>
 
Example use:
 
<syntaxhighlight lang="text"> jsonParse'{ "blue": [1,2], "ocean": "water" }'
┌────────────────┐
│┌──────┬───────┐│
Line 2,035 ⟶ 2,272:
└──────────────────────────────┘
jsonSerialize jsonParse'{ "blue": [1,2], "ocean": "water" }'
[[["\"blue\"","\"ocean\""],[["1","2"],"\"water\""]]]</langsyntaxhighlight>
 
Note that these are not strict inverses of each other. These routines allow data to be extracted from json and packed into json format, but only in a minimalistic sense. No attempts are made to preserve the subtleties of type and structure which json can carry. This should be good enough for most applications which are required to deal with json but will not be adequate for ill behaved applications which exploit the typing mechanism to carry significant information.
Line 2,043 ⟶ 2,280:
=={{header|Java}}==
This uses [http://code.google.com/p/google-gson/ Gson], a library to convert JSON to Java objects and vice-versa.
<langsyntaxhighlight Javalang="java">import com.google.gson.Gson;
 
public class JsonExample {
Line 2,085 ⟶ 2,322:
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Requires JSON library, now present in all major browsers.
<langsyntaxhighlight JavaScriptlang="javascript">var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
 
var sample = { "blue": [1,2], "ocean": "water" };
var json_string = JSON.stringify(sample);</langsyntaxhighlight>
 
JSON is called ''JavaScript'' Object Notation, but JSON differs form JavaScript object literal. cf. [https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON MDN/JSON]
Line 2,098 ⟶ 2,335:
=={{header|jq}}==
 
JSON is jq's native data format, so nothing need be done to parse JSON input. For example, to "pretty print" a stream of JSON entities (including scalars), it would be sufficient to use the jq program:<syntaxhighlight lang ="jq"> . </langsyntaxhighlight>
 
Here are the jq equivalents of the examples given in the section on Julia, assuming the file data.json holds the following JSON text:
Line 2,104 ⟶ 2,341:
{ "blue": [1,2], "ocean": "water" }
 
<syntaxhighlight lang ="jq">jq -c . data.json</langsyntaxhighlight>
produces:
 
{"blue":[1,2],"ocean":"water"}
 
<syntaxhighlight lang ="jq">jq tostring data.json</langsyntaxhighlight>
produces:
"{\"blue\":[1,2],\"ocean\":\"water\"}"
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">prompt$ jsish
Jsish interactive: see 'help [cmd]'
# var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
Line 2,127 ⟶ 2,364:
 
# puts(JSON.stringify(sample))
{ "blue":[ 1, 2 ], "ocean":"water" }</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia"># Pkg.add("JSON") ... an external library http://docs.julialang.org/en/latest/packages/packagelist/
using JSON
 
Line 2,144 ⟶ 2,381:
@assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}"
@assert jsonobj == Dict("ocean" => "water", "blue" => [1, 2])
@assert typeof(jsonobj) == Dict{String, Any}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
We use Kotlin JS here to obtain access to the JavaScript JSON object:
<langsyntaxhighlight lang="scala">// version 1.2.21
 
data class JsonObject(val foo: Int, val bar: Array<String>)
Line 2,162 ⟶ 2,399:
val data2 = JsonObject2("water", arrayOf(1, 2))
println(JSON.stringify(data2))
}</langsyntaxhighlight>
 
{{out}}
Line 2,171 ⟶ 2,408:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// Javascript objects are represented by maps in Lasso
local(mymap = map(
'success' = true,
Line 2,205 ⟶ 2,442:
'<br />'
 
json_deserialize(#myjson) // map(Closed = array(Wednesday, Thursday, Friday), numeric = 11, Open = array(Monday, Tuesday), string = Eleven, success = true)</langsyntaxhighlight>
 
=={{header|LFE}}==
Line 2,212 ⟶ 2,449:
 
===Encoding===
<langsyntaxhighlight lang="lisp">
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14))
</syntaxhighlight>
</lang>
 
The result from that can be made a little more legible with the following:
<langsyntaxhighlight lang="lisp">
(: erlang binary_to_list
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14)))
</syntaxhighlight>
</lang>
 
===Decoding===
We can run the encoding example in reverse, and get back what we put in above with the following:
<langsyntaxhighlight lang="lisp">
(: jiffy decode '"[1,2,3,[97,112,112,108,101],true,3.14]")
</syntaxhighlight>
</lang>
 
Here's a key-value example:
<langsyntaxhighlight lang="lisp">
(: jiffy decode '"{\"foo\": [1, 2, 3]}")
</syntaxhighlight>
</lang>
 
===Decoding to Patterns===
We can also extract the key and value using Erlang patterns:
<langsyntaxhighlight lang="lisp">
(let (((tuple (list (tuple key value)))
(: jiffy decode '"{\"foo\": [1, 2, 3]}")))
(: io format '"~p: ~p~n" (list key value)))
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
Line 2,247 ⟶ 2,484:
 
JavaScript movie script "JSON":
<langsyntaxhighlight lang="javascript">//--------------------------------------
// Simple (unsafe) JSON decoder based on eval()
// @param {string} json
Line 2,291 ⟶ 2,528:
return hash[c]
});
}</langsyntaxhighlight>
 
Lingo movie script "JSON":<langsyntaxhighlight lang="lingo">----------------------------------------
-- JSON encoder
-- Supported Lingo data types: VOID, integer, float, string, symbol, list, propList
Line 2,342 ⟶ 2,579:
delete the last char of str
return str
end</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lingo">data_org = [\
42,\
3.14159,\
Line 2,360 ⟶ 2,597:
-- [42, 3.1416, [2, 4, #fooBar, "apples", "bananas", "cherries"], ["foo": 1, #bar: <Void>, "Hello": "world!"], <Void>]
put data_decoded
-- [42, 3.1416, [2, 4, #fooBar, "apples", "bananas", "cherries"], ["foo": 1, #bar: <Void>, "Hello": "world!"], <Void>]</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 2,366 ⟶ 2,603:
Using the [http://www.eharning.us/wiki/luajson/ luajson] library:
 
<langsyntaxhighlight lang="lua">local json = require("json")
 
local json_data = [=[[
Line 2,403 ⟶ 2,640:
}
 
print("JSON from new Lua data: " .. json.encode(data))</langsyntaxhighlight>
 
Since in Lua <code>nil</code> signifies an ''undefined'' value, i.e. a variable or table entry with a <code>nil</code> value is undistinguishabletreated fromas the same as 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.
Line 2,445 ⟶ 2,682:
=={{header|M2000 Interpreter}}==
We use a class written in M2000 for Json [[M2000 Interpreter Json Class]] in a module LIB1
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
MODULE A {
\\ Process data in json format
Line 2,557 ⟶ 2,794:
// call A
A
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">> JSON:-ParseString("[{\"tree\": \"maple\", \"count\": 21}]");
[table(["tree" = "maple", "count" = 21])]
> JSON:-ToString( [table(["tree" = "maple", "count" = 21])] );
"[{\"count\": 21, \"tree\": \"maple\"}]"</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"]
<lang Mathematica>
ExportString[data, "JSON"]</syntaxhighlight>
data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"]
ExportString[data, "JSON"]
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight lang="matlab">>> jsondecode('{ "foo": 1, "bar": [10, "apples"] }')
ans =
struct with fields:
Line 2,580 ⟶ 2,815:
>> jsonencode(ans)
ans =
{"foo":1,"bar":[10,"apples"]}</langsyntaxhighlight>
The toolbox [http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?jsonlab/Download JSONlab] is doing a nice job to read (loadjson.m) and write (savejson.m) data in JSON format.
 
Line 2,586 ⟶ 2,821:
===json.org Library===
This uses a library provided by [http://www.json.org/java/index.html json.org] to serialize/deserialize JSON objects.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,723 ⟶ 2,958:
ts.append(']')
return ts.toString()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,764 ⟶ 2,999:
===Google gson Library===
This uses [http://code.google.com/p/google-gson/ Gson], a library to convert JSON to Java objects and vice-versa.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,845 ⟶ 3,080:
ts.append(']')
return ts.toString()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,875 ⟶ 3,110:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import json
 
var data = parseJson("""{ "foo": 1, "bar": [10, "apples"] }""")
Line 2,882 ⟶ 3,117:
 
var js = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}]
echo js</langsyntaxhighlight>
{{out}}
<pre>1
[ 10, "apples"]
[ { "name": "John", "age": 30 }, { "name": "Susan", "age": 31 }]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use Struct;
use JSON;
Line 2,903 ⟶ 3,138:
}
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|Mac OS X|10.7+|Xcode 4.4+}}
<langsyntaxhighlight lang="objc">NSString *jsonString = @"{ \"foo\": 1, \"bar\": [10, \"apples\"] }";
id obj = [NSJSONSerialization
JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding]
Line 2,921 ⟶ 3,156:
encoding: NSUTF8StringEncoding];
NSLog(@"%@", jsonString2);
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 2,930 ⟶ 3,165:
{{libheader|json-static}}
 
<langsyntaxhighlight lang="ocaml">type json item =
< name "Name": string;
kingdom "Kingdom": string;
Line 2,953 ⟶ 3,188:
let () =
let j = Json_io.json_of_string str in
print_endline (Json_io.string_of_json j);</langsyntaxhighlight>
 
compile with:
Line 2,962 ⟶ 3,197:
{{libheader|yojson}}
 
<langsyntaxhighlight lang="ocaml">open Yojson.Basic.Util
 
let s = "
Line 2,992 ⟶ 3,227:
let () =
let json = Yojson.Basic.from_string s in
List.iter print_endline (extract_titles json)</langsyntaxhighlight>
 
Compile and run:
Line 3,013 ⟶ 3,248:
A Json object can be converted to a string using #asString
 
<langsyntaxhighlight Oforthlang="oforth">>{"parents":["Otmar Gutmann", "Silvio Mazzola"], "name":"Pingu", "born":1986} .s
[1] (Json) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" : 1986 }
ok
Line 3,022 ⟶ 3,257:
[1] (Json) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" : 1986 }
ok
></langsyntaxhighlight>
 
=={{header|Ol}}==
Ol comes with library that provides JSON parsing and forming.
 
<langsyntaxhighlight lang="scheme">
(import (file json))
 
Line 3,074 ⟶ 3,309:
}
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,087 ⟶ 3,322:
=={{header|OpenEdge/Progress}}==
The WRITE-JSON and READ-JSON methods were introduced in Progress OpenEdge 10.2B.
<langsyntaxhighlight lang="progress">/* using a longchar to read and write to, can also be file, memptr, stream */
DEFINE VARIABLE lcjson AS LONGCHAR NO-UNDO.
 
Line 3,120 ⟶ 3,355:
example.blue [1] example.blue [2] SKIP
example.ocean
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
{{out}} write-json:
Line 3,157 ⟶ 3,392:
=={{header|Oz}}==
Using the [http://code.google.com/p/oz-code/downloads/list google.com/oz-code] JSON library:
<langsyntaxhighlight lang="oz">declare
[JSON] = {Module.link ['JSON.ozf']}
 
Line 3,163 ⟶ 3,398:
 
Sample = object(blue:array(1 2) ocean:"water")
{System.showInfo {JSON.encode Sample}}</langsyntaxhighlight>
 
{{out}}
<pre>object(bar:array(10 [97 112 112 108 101 115]) foo:1)
{"blue":[1,2],"ocean":"water"}</pre>
 
=={{header|Pascal}}==
Works with FPC (tested with version 3.2.2).
<syntaxhighlight lang="pascal">
program test;
{$mode objfpc}{$h+}
uses
FpJson, JsonParser;
 
const
JsonValue =
'{ ' + LineEnding +
' "answer": { ' + LineEnding +
' "everything": 42 ' + LineEnding +
' }, ' + LineEnding +
' "happy": true, ' + LineEnding +
' "list": [ ' + LineEnding +
' 0, ' + LineEnding +
' 1, ' + LineEnding +
' 2 ' + LineEnding +
' ], ' + LineEnding +
' "name": "Pierrot", ' + LineEnding +
' "nothing": null, ' + LineEnding +
' "object": { ' + LineEnding +
' "product": "unknown",' + LineEnding +
' "amount": 1001 ' + LineEnding +
' }, ' + LineEnding +
' "pi": 3.1416 ' + LineEnding +
'} ';
 
function JsonsEqual(L, R: TJsonData): Boolean;
var
I: Integer;
e: TJsonEnum;
d: TJsonData;
begin
if (L = nil) or (R = nil) then exit(False);
if L = R then exit(True);
if (L.JSONType <> R.JSONType) or (L.Count <> R.Count) then exit(False);
case L.JSONType of
jtUnknown: exit(False);
jtNull: ;
jtBoolean: exit(L.AsBoolean = R.AsBoolean);
jtNumber: exit(L.AsFloat = R.AsFloat);
jtString: exit(L.AsString = R.AsString);
jtArray:
for I := 0 to Pred(L.Count) do
if not JsonsEqual(L.Items[I], R.Items[I]) then exit(False);
jtObject:
for e in L do begin
if not TJsonObject(R).Find(e.Key, d) then exit(False);
if not JsonsEqual(e.Value, d) then exit(False);
end;
end;
Result := True;
end;
 
var
Expected, HandMade: TJsonData;
 
begin
Expected := GetJson(JsonValue);
HandMade := CreateJSONObject([
'answer', CreateJSONObject(['everything', 42]),
'happy', True,
'list', CreateJSONArray([0, 1, 2]),
'name', 'Pierrot',
'nothing', CreateJSON,
'object', CreateJSONObject(['product', 'unknown', 'amount', 1001]),
'pi', 3.1416
]);
WriteLn(HandMade.FormatJson);
WriteLn;
if JsonsEqual(Expected, HandMade) then
WriteLn('Objects look identical')
else
WriteLn('Oops, something went wrong');
Expected.Free;
HandMade.Free;
end.
</syntaxhighlight>
 
=={{header|Perl}}==
{{libheader|JSON}}
<langsyntaxhighlight lang="perl">use JSON;
 
my $data = decode_json('{ "foo": 1, "bar": [10, "apples"] }');
 
my $sample = { blue => [1,2], ocean => "water" };
my $json_string = encode_json($sample);</langsyntaxhighlight>
 
=={{header|Phix}}==
The distribution now contains a simple json module
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>--
<span style="color: #000080;font-style:italic;">-- demo\rosetta\JSON.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
-- =====================
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">json</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
--
include builtins/json.e
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"roundtrip (10 examples):\n"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">json_strings</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">`{"this":"that","age":{"this":"that","age":29}}`</span><span style="color: #0000FF;">,</span>
puts(1,"roundtrip (10 examples):\n")
<span style="color: #008000;">`1`</span><span style="color: #0000FF;">,</span>
sequence json_strings = {"{\"this\":\"that\",\"age\":{\"this\":\"that\",\"age\":29}}",
<span style="1color: #008000;">`"hello"`</span><span style="color: #0000FF;">,</span>
<span style="\color: #008000;"hello\>`null`</span><span style="color: #0000FF;">,</span>
<span style="nullcolor: #008000;">`[12]`</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">`[null,12]`</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">`[null,12]`</span><span style="color: #0000FF;">,</span>
<span style="[]color: #008000;">`{"this":"that","age":29}`</span><span style="color: #0000FF;">,</span>
<span style="{\"this\"color:\ #008000;"that\",\"age\>`{}`</span><span style="color:29} #0000FF;">,</span>
<span style="{}color: #008000;">`[null,[null,12]]`</span><span style="color: #0000FF;">}</span>
"[null,[null,12]]"}
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">json_strings</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
 
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">json_strings</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
for i=1 to length(json_strings) do
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
string s = json_strings[i]
<span style="color: #004080;">object</span> <span style="color: #000000;">json_object</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">parse_json</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
puts(1,s&"\n")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">print_json</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">json_object</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
object json_object = parse_json(s)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">print_json</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">json_object</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
puts(1,print_json("",json_object,true)&"\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if not equal(print_json("",json_object,true),s) then ?9/0 end if
<!--</syntaxhighlight>-->
end for</lang>
{{out}}
<pre>
Line 3,231 ⟶ 3,547:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays
Line 3,237 ⟶ 3,553:
$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp has no JSON library, but it is easy enough to write one. The following supports only fixpoint numbers (no floating point, as it doesn't exist in PicoLisp). Arrays and objects are both mapped to lists.
<langsyntaxhighlight PicoLisplang="picolisp">(de checkJson (X Item)
(unless (= X Item)
(quit "Bad JSON" Item) ) )
Line 3,289 ⟶ 3,605:
(and (cdr X) (prin ", ")) )
Item )
(prin "}") ) ) )</langsyntaxhighlight>
This reads/prints JSON from/to files, pipes, sockets etc. To read from a string, a pipe can be used:
<pre>: (pipe (prinl "{ \"foo\": 1, \"bar\": [10, \"apples\"] }")
Line 3,308 ⟶ 3,624:
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">int main() {
// Decoding
string json = "{\"cake\":[\"desu\",1,2.3],\"foo\":1}";
Line 3,320 ⟶ 3,636:
write("%s\n", Standards.JSON.encode(m));
}</langsyntaxhighlight>
 
<pre>([ /* 2 elements */
Line 3,334 ⟶ 3,650:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
# JSON input is being stored in ordered hashtable.
# Ordered hashtable is available in PowerShell v3 and higher.
Line 3,342 ⟶ 3,658:
# If you use the Invoke-RestMethod cmdlet there is not need for the ConvertFrom-Json cmdlet
Invoke-WebRequest -Uri "http://date.jsontest.com" | ConvertFrom-Json
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
{
"foo": 1,
Line 3,356 ⟶ 3,672:
---- ------------------------ ----
12:25:25 PM 1414326325923 10-26-2014
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Line 3,362 ⟶ 3,678:
Using SWI-Prolog 7's library(http/json), and the new dict datatype, there is nearly transparent handling of JSON objects. All of the serialization and parsing in the following code is accomplished with two predicates. The rest of the code is for the sake of example.
 
<langsyntaxhighlight Prologlang="prolog">:- use_module([ library(http/json),
library(func) ]).
 
Line 3,383 ⟶ 3,699:
year:1985
}},
json_write(current_output, Dict). %% This accomplishes serializing the JSON object.</langsyntaxhighlight>
 
{{out}} from these two example predicates:
<langsyntaxhighlight Prologlang="prolog">?- reading_JSON_term.
JSON as Prolog dict: _G5217{widget:_G5207{debug:on,image:_G5123{alignment:center,hOffset:250,name:sun1,src:Images/Sun.png,vOffset:250},text:_G5189{alignment:center,data:Click Here,hOffset:250,name:text1,onMouseUp:sun1.opacity = (sun1.opacity / 100) * 90;,size:36,style:bold,vOffset:100},window:_G5077{height:500,name:main_window,title:Sample Konfabulator Widget,width:500}}}
 
Line 3,404 ⟶ 3,720:
}
}
true.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">OpenConsole()
If CreateJSON(1)
PB_Team_Members=SetJSONObject(JSONValue(1))
Line 3,440 ⟶ 3,756:
PrintN(Mid(PB_Special_thanks$,JSONErrorPosition()+1))
EndIf
Input()</langsyntaxhighlight>
{{out}}
<pre>PureBasic - Team Members:
Line 3,463 ⟶ 3,779:
=={{header|Python}}==
{{works with|Python|2.6+}}{{works with|Python|3.0+}}
<langsyntaxhighlight Pythonlang="python">>>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
Line 3,472 ⟶ 3,788:
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}</langsyntaxhighlight>
 
Because most of JSON is valid Python syntax (except "true", "false", and "null", and a few obscure escape sequences), it is also possible (but not recommended) to parse JSON using eval():
<langsyntaxhighlight lang="python">>>> true = True; false = False; null = None
>>> data = eval('{ "foo": 1, "bar": [10, "apples"] }')
>>> data
{'foo': 1, 'bar': [10, 'apples']}</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">library(rjson)
data <- fromJSON('{ "foo": 1, "bar": [10, "apples"] }')
data</langsyntaxhighlight>
<pre>data
$foo
Line 3,495 ⟶ 3,811:
[1] "apples"
</pre>
<syntaxhighlight lang R="r">cat(toJSON(data))</langsyntaxhighlight>
<pre>{"foo":1,"bar":[10,"apples"]}</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,508 ⟶ 3,824:
 
(write-json '(1 2 "three" #hash((x . 1) (y . 2) (z . 3))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,515 ⟶ 3,831:
Using [http://github.com/moritz/json/ JSON::Tiny]
 
<syntaxhighlight lang="raku" perl6line>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);</lang>
<pre>{bar => [10 apples], foo => 1}
{ "blue" : [ 1, 2 ], "ocean" : "water" }</pre>
 
=={{header|REBOL}}==
Using [http://www.json.org/json.r json.org/json.r]
 
<langsyntaxhighlight lang="rebol">json-str: {{"menu": {
"id": "file",
"string": "File:",
Line 3,539 ⟶ 3,857:
res: json-to-rebol json-str
js: rebol-to-json res
</syntaxhighlight>
</lang>
 
json-to-rebol Result:
Line 3,577 ⟶ 3,895:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'json'
 
ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}')
Line 3,584 ⟶ 3,902:
ruby_obj["ocean"] = { "water" => ["fishy", "salty"] }
puts JSON.generate(ruby_obj)
puts JSON.pretty_generate(ruby_obj)</langsyntaxhighlight>
 
{{out}}
Line 3,608 ⟶ 3,926:
{{works with|Rust|1.31}}
{{libheader|Serde|1.0}}
<langsyntaxhighlight lang="toml">[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"</langsyntaxhighlight>
 
Serde is a general serialization/deserialization library. Serde-JSON implements JSON serialization for Serde.
Line 3,616 ⟶ 3,934:
Using said library is quite straight forward, one simply derives <code>Serialize</code>/<code>Deserialize</code> onto the types they want to convert into and from JSON strings.
 
<langsyntaxhighlight lang="rust">use serde::{Serialize, Deserialize};
 
#[derive(Serialize, Deserialize, Debug)]
Line 3,622 ⟶ 3,940:
x: i32,
y: i32,
}</langsyntaxhighlight>
 
Said type could then be used as such:
 
<langsyntaxhighlight lang="rust">fn main() {
let point = Point { x: 1, y: 2 };
 
Line 3,634 ⟶ 3,952:
println!("serialized = {}", serialized);
println!("deserialized = {:?}", deserialized);
}</langsyntaxhighlight>
 
The result of which is type-checked JSON (where extra entries get ignored), without need of a key-value container.
Line 3,644 ⟶ 3,962:
It also handles more Rust specific types like enums, tuples, struct tuples, and zero-sized types.
 
<langsyntaxhighlight lang="rust">#[derive(Serialize, Deserialize)]
struct W { a: i32, b: i32 } // => { "a": 0, "b": 0 }
 
Line 3,662 ⟶ 3,980:
Y(i32), // => { "Y": 0 }
Z, // => { "Z" }
}</langsyntaxhighlight>
 
The traits are also implemented for <code>HashMap</code> and <code>Vec</code> which can be used as conventional objects/arrays, on top of macros and <code>serde_json::Value</code> to handle all other potentially weird edge cases.
 
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
use serde_json::Value;
 
Line 3,675 ⟶ 3,993:
#[serde(flatten)]
metadata: HashMap<String, Value>,
}</langsyntaxhighlight>
 
In this example <code>metadata</code> would simply capture all other additional entries, for example:
 
<langsyntaxhighlight lang="rust">fn main() {
let data = {
let mut metadata = HashMap::new();
Line 3,696 ⟶ 4,014:
println!("serialized = {}", serialized);
println!("deserialized = {:?}", deserialized);
}</langsyntaxhighlight>
{{out}}
<pre>serialized = {"points":[{"x":1,"y":2},{"x":15,"y":32}],"square":false,"triangle":3}
Line 3,705 ⟶ 4,023:
Using the builtin parsing lib (debatably slower than third-party libs such as lift-json from Liftweb).
 
<langsyntaxhighlight lang="scala">scala> import scala.util.parsing.json.{JSON, JSONObject}
import scala.util.parsing.json.{JSON, JSONObject}
 
Line 3,713 ⟶ 4,031:
scala> JSONObject(Map("foo" -> "bar")).toString()
res1: String = {"foo" : "bar"}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
Using the [http://api.call-cc.org/doc/json json] egg: <langsyntaxhighlight lang="scheme">
(use json)
(define object-example
Line 3,730 ⟶ 4,048:
; this writes the following:
; {"foo": "bar", "baz": [1, 2, 3], "qux": {"foo": "bar"}}
</syntaxhighlight>
</lang>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight SenseTalklang="sensetalk">set jsonString to <<{"foo": 10, "bar": [1, 2, 3]}>>
put JSONValue(jsonString)
 
set dataObject to (string_value: "lorem ipsum", int_value: 314, array_value: (2, 4, 6))
put JSONFormat(dataObject)</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight 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);</langsyntaxhighlight>
{{out}}
<pre>Hash.new(
'"blue'" => [1, 2],
'"ocean'" => '"water'"
)
)
{"blue":[1,2],"ocean":{"water":["fishy","salty"]}}</pre>
 
=={{header|Smalltalk}}==
Use the NeoJSON library: [http://smalltalkhub.com/#!/~SvenVanCaekenberghe/Neo NeoJSON]
<langsyntaxhighlight lang="smalltalk">
NeoJSONReader fromString: '{ "foo": 1, "bar": [10, "apples"] }'.
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,765 ⟶ 4,083:
=={{header|Standard ML}}==
Works on Unix/Linux/BSD with jq (github.com/stedolan/jq/ ) installed. Data storage in strings, so floating point numbers can be written back as received, in a recursive polymorphic structure, which can also be used to store the data as SML-types. (Without Jq on the system or on Microsoft systems, delete the Validate function and its call, and the code can be used for valid JSON-strings without any white space outside strings (only).)
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val Validate = fn jsonstring =>
let
Line 3,894 ⟶ 4,212:
 
end ;
</langsyntaxhighlight>Example
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val testString="{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,\"address\":{\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\",\"postalCode\":\"10021\"},\"phoneNumber\":[{\"type\":\"home\",\"numbers\":[{\"o\":\"212 555-1234\",\"h\":\"119 323-1234\"}]},{\"type\":\"fax\",\"number\":\"646 555-4567\"}]}" ;
 
Line 3,925 ⟶ 4,243:
elem (St "postalCode", value (St "10021"))]):
(jvals, jvals content) element
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
Line 3,946 ⟶ 4,264:
print("JSON: \(jsonString2)")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,967 ⟶ 4,285:
=={{header|Tailspin}}==
A JSON parser and printer can fairly easily be created
<langsyntaxhighlight lang="tailspin">
// Not all JSON object member keys can be represented, a fallback would need to be implemented
// Currently Tailspin only supports integers so for now we leave numbers as strings, as we do for true, false and null
Line 3,973 ⟶ 4,291:
templates hexToInt
templates hexDigit
<='0'> 0! <='1'> 1! <='2'> 2! <='3'> 3! <='4'> 4! <='5'> 5! <='6'> 6! <='7'> 7! <='8'> 8! <='9'> 9!
<'[Aa]'> 10! <'[Bb]'> 11! <'[Cc]'> 12! <'[Dd]'> 13! <'[Ee]'> 14! <'[Ff]'> 15!
end hexDigit
Line 3,985 ⟶ 4,303:
rule value: (<WS>?) <string|number|object|array|true|false|null> (<WS>?)
 
rule string: (<='"'>) <chars> (<='"'>)
rule chars: [ <quote|backslash|slash|backspace|formfeed|linefeed|return|tab|unicode|'[^"]'>* ] -> '$...;'
rule quote: <='\\"'> -> '"'
rule backslash: <='\\\\'> -> '\'
rule slash: <='\\/'> -> '/'
rule backspace: <='\\b'> -> '$#8;'
rule formfeed: <='\\f'> -> '$#12;'
rule linefeed: <='\\n'> -> '$#10;'
rule return: <='\\r'> -> '$#13;'
rule tab: <='\\t'> -> '$#9;'
rule unicode: (<='\\u'>) <'[0-9A-Fa-f]{4}'> -> hexToInt -> '$#$;'
 
rule number: <'-?(0|[1-9][0-9]*)(\.[0-9]+)?((e|E)(\+|-)?[0-9]+)?'> // TODO: represent this other than string
 
rule object: (<='\{'> <WS>?) { <keyValues>? } (<='}'>)
rule keyValues: <keyValue> <followingKeyValue>*
rule keyValue: <string>: (<WS>? <=':'>) <value>
rule followingKeyValue: (<=','> <WS>?) <keyValue>
 
rule array: (<='\['>) [ <arrayValues>? ] (<=']'>)
rule arrayValues: <value> <followingArrayValue>*
rule followingArrayValue: (<=','>) <value>
 
rule true: <='true'> // TODO: represent this other than string
rule false: <='false'> // TODO: represent this other than string
rule null: <='null'> // TODO: represent this other than string
end jsonParser
 
Line 4,018 ⟶ 4,336:
end printKeyValue
templates encodeChars
<='"'> '\"' !
<='\\'> '\\' !
<='/'> '\/' !
<='$#8;'> '\b' !
<='$#12;'> '\f' !
<='$#10;'> '\n' !
<='$#13;'> '\r' !
<='$#9;'> '\t' !
<> $ !
end encodeChars
Line 4,033 ⟶ 4,351:
when <{}> do
[ $... ] -> '{$(1) -> printKeyValue;$(2..last)... -> ', $ -> printKeyValue;';}' !
when <..0|0..> do
'$;'!
when <'.*'> do
[ $... -> encodeChars ] -> '"$...;"' !
otherwise 'WTF!' !
// Other types do not yet exist in Tailspin
end printJson
 
</lang>
Then, called as below:
<lang tailspin>
'{ "foo": 1, "bar": [10, "apples"] }' -> jsonParser -> '$.bar(2);
' -> !OUT::write
 
{ blue: [1,2], ocean: 'water' } -> printJson -> '$;
' -> !OUT::write
 
</lang>
'plain string
' -> printJson -> '$;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
apples
{"blue": [1, 2], "ocean": "water"}
"plain string\n"
</pre>
 
=={{header|Tcl}}==
For parsing JSON, {{tcllib|json}} provides the capability (see [http://wiki.tcl.tk/13419 the Tcler's Wiki page on it] for more discussion):
<langsyntaxhighlight lang="tcl">package require json
set sample {{ "foo": 1, "bar": [10, "apples"] }}
 
set parsed [json::json2dict $sample]
puts $parsed</langsyntaxhighlight>
{{out}}
<pre>foo 1 bar {10 apples}</pre>
Line 4,068 ⟶ 4,389:
{{works with|Tcl|8.6}}
{{tcllib|json::write}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require json::write
 
Line 4,109 ⟶ 4,430:
}
}
}</langsyntaxhighlight>
Sample code (note that the value is built with <code>dict create</code> and <code>list</code> so that there is some auxiliary type hints available, which the above procedure can read):
<langsyntaxhighlight lang="tcl">set d [dict create blue [list 1 2] ocean water]
puts [tcl2json $d]</langsyntaxhighlight>
{{out}}
<pre>
Line 4,124 ⟶ 4,445:
=={{header|TXR}}==
 
===ParsingBuilt-In===
 
TXR has built in JSON support.
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]].
 
The TXR Lisp syntax supports JSON literals, which are prefixed with <code>#J</code>.
It 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.
 
<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.
 
This is implemented with recursive horizontal pattern matching functions, and so basically the definition resembles a grammar. Horizontal functions 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,134 ⟶ 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.
 
<langsyntaxhighlight lang="txr">@(define value (v))@\
@(cases)@\
@(string v)@(or)@(num v)@(or)@(object v)@(or)@\
Line 4,194 ⟶ 4,620:
@(end)
@(freeform)
@(maybe)@(value v)@(end)@badsyntax</langsyntaxhighlight>
 
A few tests. Note, the <code>badsyntax</code> variable is bound to any trailing portion of the input that does not match the syntax. The call to the parser <code>@(value v)</code> extracts the longest prefix of the input which is consistent with the syntax, leaving the remainder to be matched into <code>badsyntax</code>.
 
<langsyntaxhighlight lang="bash">$ echo -n '{ "a" : { "b" : 3, "c" : [1,2,3] } }[' | ./txr -l json.txr -
(v "O" ((("S" "a") ("O" ((("S" "b") ("N" "3")) (("S" "c") ("A" (("N" "1") ("N" "2") ("N" "3")))))))))
(badsyntax . "[\n")
Line 4,204 ⟶ 4,630:
$ echo -n '"\u1234"' | ./txr -l json.txr -
(v "S" "\11064")
(badsyntax . "")</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import json
 
struct User {
// Adding a [required] attribute will make decoding fail, if that
// field is not present in the input.
// If a field is not [required], but is missing, it will be assumed
// to have its default value, like 0 for numbers, or '' for strings,
// and decoding will not fail.
name string [required]
age int
// Use the `skip` attribute to skip certain fields
foo int [skip]
// If the field name is different in JSON, it can be specified
last_name string [json: lastName]
possessions []string
}
 
fn main() {
data := '{ "name": "Frodo", "lastName": "Baggins", "age": 25, "possessions": ["shirt","ring","sting"] }'
user := json.decode(User, data) or {
eprintln('Failed to decode json, error: $err')
return
}
println(user)
 
println(json.encode(user))
}</syntaxhighlight>
 
{{out}}
<pre>
User{
name: 'Frodo'
age: 25
foo: 0
last_name: 'Baggins'
possessions: ['shirt', 'ring', 'sting']
}
{"name":"Frodo","age":25,"lastName":"Baggins","possessions":["shirt","ring","sting"]}
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-json}}
<langsyntaxhighlight ecmascriptlang="wren">import "/json" for JSON
 
var s = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"
Line 4,216 ⟶ 4,683:
o = { "blue": [1, 2], "ocean": "water" }
s = JSON.stringify(o)
System.print(s)</langsyntaxhighlight>
 
{{out}}
Line 4,227 ⟶ 4,694:
 
The XPath 3.1 standard specifies an XML format to store JSON information. Different XQuery processors implement their own JSON parsers in addition to the XPath functions. One such function has been added, to show, how to map JSON into an XPath map using the BaseX processor. As XQuery is a superset of XPath, the following code is valid XQuery 3.1. Except for 'null', which does not exist in the XPath data model, all JSON datatypes have their XPath equivalent. 'Null' is being represented by the empty sequence. This gets shown at the last function invocation, which creates an XPath map. It may be interesting to note, that the different options for the json serializers and parsers have not been used here.
<langsyntaxhighlight lang="xquery">
let $json := '
{
Line 4,257 ⟶ 4,724:
)
 
</syntaxhighlight>
</lang>
 
Result:
Line 4,320 ⟶ 4,787:
 
To convert from JSON to zkl:
<langsyntaxhighlight lang="zkl">a,b:=Import.lib("zklYAJL");
var [const] YAJL=a, toJSON=b;
src:=
Line 4,338 ⟶ 4,805:
obj:=YAJL().write(src).close();
// or obj:=src.pump(YAJL()).close(); // for example, from file or socket
obj.println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,344 ⟶ 4,811:
</pre>
From zkl to JSON:
<langsyntaxhighlight lang="zkl">// using above code plus:
toJSON(obj).println();</langsyntaxhighlight>
{{out}}
<pre>{"pi":3.1400000000,"an array":[-1,true,false,null,"foo"],"large number":123456789123456791}
9,476

edits