JSON: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Specified task, and separated the inverse task into a separate page.) |
m (→{{header|Wren}}: Minor tidy) |
||
(33 intermediate revisions by 22 users not shown) | |||
Line 1:
{{task}}
Also, create a new data structure and serialize it into JSON.
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}}==
8th uses JSON as its data description language, so:
Line 24 ⟶ 80:
=={{header|Ada}}==
=== Alternative using GNATCOLL ===
<
with Ada.Text_IO;
with GNATCOLL.JSON;
Line 66 ⟶ 122:
Put_Line (Penguin.Write);
end JSON_Test;
</syntaxhighlight>
{{out}}
Line 76 ⟶ 132:
=== Alternative using Matreshka ===
<
with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO;
with League.JSON.Arrays; use League.JSON.Arrays;
Line 118 ⟶ 174:
Put_Line (To_JSON_Document (Penguin).To_JSON.To_Wide_Wide_String);
end Main;
</syntaxhighlight>
{{out}}
Line 128 ⟶ 184:
=={{header|AntLang}}==
JSON parser (maybe failes with "invalid JSON" error)
<syntaxhighlight lang="antlang">
json:{[data]catch[eval[,|{[y]catch[{":" = "="; "[" = "<"; "]" = ">"; "," = ";"}[y];{x};{[]y}]}'("""("(\\.|[^\\"])*"|\-?[0-9]+(\.[0-9]+)?|\{|\}|\[|\]|\:|\,)"""~data)["strings"]];{x};{error["Invalid JSON"]}]}
</syntaxhighlight>
=={{header|ANTLR}}==
Line 143 ⟶ 199:
===Java===
<
// Parse JSON
//
Line 167 ⟶ 223:
| array;
array : '[' {System.out.println(Indent + "Array"); Indent += " ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};
</syntaxhighlight>
Produces:
<pre>
Line 206 ⟶ 262:
=={{header|Apex}}==
JSON serialization and deserialization is built in
<
String foo {get;set;}
Integer bar {get;set;}
Line 220 ⟶ 276:
//"testObj.foo == deserializedObject.foo" is true
//"testObj.bar == deserializedObject.bar" is true
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print read.json {{ "foo": 1, "bar": [10, "apples"] }}
object: #[
name: "john"
surname: "doe"
address: #
number: 10
street: "unknown"
country: "Spain"
]
married: false
]
{{out}}
<pre>
{
"name": "john",
Line 275 ⟶ 314:
A full roundtrip from JSON file over a Bracmat internal representation back to a JSON file looks like this:
<
Let us split this into separate steps.
Line 281 ⟶ 320:
To read a JSON file "myfile.json", use
<
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:
<
To convert the corresponding Bracmat data structure <code>(,1 2 3)</code> back to a JSON string, use
<syntaxhighlight lang
To write a JSON string <code>"[1,2,3]"</code> to a file "array.json", use
<
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 343 ⟶ 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:
<
( get$("rosetta.json",JSN):?json
& lst$(json,"json.bra",NEW)
& put$(jsn$!json,"rosetta-roundtrip.json",NEW)
)</
rosetta.json:
Line 524 ⟶ 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.
<
#include <stdlib.h>
#include <string.h>
Line 643 ⟶ 682:
return EXIT_SUCCESS;
}</
{{out}}
Line 676 ⟶ 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.
<
using System.Collections.Generic;
using System.Web.Script.Serialization;
Line 698 ⟶ 737:
Console.WriteLine(array[1]);
}
}</
=={{header|C++}}==
Line 704 ⟶ 743:
{{libheader|U++}}
<
using namespace Upp;
Line 718 ⟶ 757:
Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}
</syntaxhighlight>
C++11 {{libheader|nlohmann::json}}
<
#include <iomanip> // std::setw
#include <sstream>
Line 786 ⟶ 825:
return 0;
}
</syntaxhighlight>
=={{header|Caché ObjectScript}}==
<
Class Sample.JSON [ Abstract ]
{
Line 801 ⟶ 840:
}
</syntaxhighlight>
{{out|Examples}}
<pre>
Line 853 ⟶ 892:
=={{header|Clojure}}==
Library: [https://github.com/clojure/data.json data.json]
<
; Load as Clojure data structures and bind the resulting structure to 'json-map'.
Line 862 ⟶ 901:
; Pretty-print the Clojure representation of JSON. We've come full circle.
(pprint-json json-map)</
=={{header|CoffeeScript}}==
<
sample =
blue: [1, 2]
Line 875 ⟶ 914:
console.log json_string
console.log json_obj
</syntaxhighlight>
=={{header|ColdFusion}}==
<
<!--- Create sample JSON structure --->
<cfset json = {
Line 899 ⟶ 938:
<cfdump var="#jsonSerialized#" />
<cfdump var="#jsonDeserialized#" />
</syntaxhighlight>
=={{header|Common Lisp}}==
Library: [https://github.com/hankhero/cl-json cl-json]
<
(ql:quickload '("cl-json"))
Line 914 ⟶ 953:
(json:decode-json s)))
</syntaxhighlight>
<pre>To load "cl-json":
Line 926 ⟶ 965:
=={{header|Crystal}}==
Before 1.0.0:
<syntaxhighlight lang="ruby">
require "json_mapping"
class Foo
Line 941 ⟶ 981:
puts(foo.to_json)
end
</syntaxhighlight>
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:
<pre>1 ["a", "b"]
{"num":1,"array":["a","b"]}</pre>
=={{header|D}}==
<
void main() {
auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
writeln(toJSON(&j));
}</
<pre>{"foo":1,"bar":[10,"apples"]}</pre>
=={{header|Dart}}==
<
main(){
Line 988 ⟶ 1,045:
assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}
</syntaxhighlight>
{{out}}
Line 998 ⟶ 1,055:
{{trans|JavaScript}}
<
main(){
Line 1,007 ⟶ 1,064:
var json_string = jsonEncode(sample);
}
</syntaxhighlight>
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program JsonTest;
Line 1,066 ⟶ 1,123:
Readln;
end.
</syntaxhighlight>
{{out}}
Line 1,077 ⟶ 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]].
<
;; JSON standard types : strings, numbers, and arrays (vectors)
(export-json #(6 7 8 9)) → "[6,7,8,9]"
Line 1,113 ⟶ 1,170:
→ # (simon 🎩)
</syntaxhighlight>
Line 1,120 ⟶ 1,177:
Structures used both to construct and to parse JSON strings:
<
person person;
relationships relationship[]?;
Line 1,134 ⟶ 1,191:
relationshipType string;
id int;
end</
Construct JSON string:
<
people.appendElement(new Person { firstName = "Frederick", lastName = "Flintstone", age = 35} );
Line 1,158 ⟶ 1,215:
// Show JSON string
SysLib.writeStdout(jsonString);</
{{out|Raw Output}}
Line 1,193 ⟶ 1,250:
Parse JSON:
<
family Dictionary;
jsonLib.convertFromJSON(jsonString, family);
Line 1,217 ⟶ 1,274:
end
end</
{{out}}
Line 1,246 ⟶ 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.
<
function geocode(address String) returns (GoogleGeocoding) {
@Resource{uri = "binding:GoogleGeocodingBinding"},
Line 1,260 ⟶ 1,317:
SysLib.writeStdout(result.results[1].geometry.location.lat);
SysLib.writeStdout(result.results[1].geometry.location.lng);
end</
=={{header|Elena}}==
ELENA 4.x
<
import extensions'dynamic;
Line 1,275 ⟶ 1,332:
console.printLine("json.foo=",o.foo);
console.printLine("json.bar=",o.bar)
}</
{{out}}
<pre>
Line 1,283 ⟶ 1,340:
=={{header|Emacs Lisp}}==
{{libheader|Jansson}}
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}}
{
"foo": "bar",
"baz": [
1,
2,
3
}
=={{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">
-module(json).
-export([main/0]).
Line 1,399 ⟶ 1,441:
io:format("JSON -> Erlang\n~p\n",[mochijson:decode(JSON)]),
io:format("Erlang -> JSON\n~s\n",[mochijson:encode(Erlang)]).
</syntaxhighlight>
{{out}}
Line 1,421 ⟶ 1,463:
1. Using Json.Net
<
open Newtonsoft.Json
type Person = {ID: int; Name:string}
Line 1,431 ⟶ 1,473:
let xs1 = JsonConvert.DeserializeObject<Person list>(json)
xs1 |> List.iter(fun x -> printfn "%i %s" x.ID x.Name)
</syntaxhighlight>
Print:
<
1 First
2 Second
</syntaxhighlight>
2. Using FSharp.Data
<
open FSharp.Data.JsonExtensions
Line 1,452 ⟶ 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)</
Print:
<
{
"ID": 1,
Line 1,466 ⟶ 1,508:
1 "First"
2 "Second"
</syntaxhighlight>
3. Alternative way of parsing: JsonProvider
<
type Person = {ID: int; Name:string}
type People = JsonProvider<""" [{"ID":1,"Name":"First"},{"ID":2,"Name":"Second"}] """>
Line 1,474 ⟶ 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) </
Print:<
1 First
2 Second
</syntaxhighlight>
=={{header|Factor}}==
<syntaxhighlight lang="factor">
USING: json.writer json.reader ;
Line 1,492 ⟶ 1,534:
! Create a new data structure and serialize into JSON
{ { "blue" { "ocean" "water" } } >json
</syntaxhighlight>
=={{header|Fantom}}==
<
using util
Line 1,515 ⟶ 1,557:
}
}
</syntaxhighlight>
{{out}}
Line 1,524 ⟶ 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,546 ⟶ 1,628:
</pre>
<
program json_fortran
use json_module
Line 1,595 ⟶ 1,677:
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 1,602 ⟶ 1,746:
Built-in <code>println()</code> also produces JSON conformant output.
This method only uses built-in functions but is comparatively slow.
<
Using module <code>json</code> gives better performance and also pretty prints the JSON output.
<
DefaultJSONWriter.write( JSONReader({'ints', 'bigInts'}).fromString('{ "foo": 1, "bar": [10, "apples"] }') )</
{{out}}
Line 1,620 ⟶ 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.
<
import "encoding/json"
Line 1,647 ⟶ 1,836:
fmt.Println(err)
}
}</
{{out}}
<pre>
Line 1,654 ⟶ 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.
<
import "encoding/json"
Line 1,712 ⟶ 1,901:
fmt.Println(string(jData))
}
}</
{{out}}
<pre>
Line 1,738 ⟶ 1,927:
]
</pre>
=={{header|Gosu}}==
Gosu consumes JSON as a Dynamic type via this core API:
<
gw.lang.reflect.json.Json#fromJson( String json ) : javax.script.Bindings
</syntaxhighlight>
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,749 ⟶ 1,941:
Sample Person JSON (from http://gosu-lang.github.io/data/person.json):
<
"Name": "Dickson Yamada",
"Age": 39,
Line 1,769 ⟶ 1,961:
]
}
</syntaxhighlight>
And the dynamic Gosu code to access it:
<
var personUrl = new URL( "http://gosu-lang.github.io/data/person.json" )
var person: Dynamic = personUrl.JsonContent
print( person.Name )
</syntaxhighlight>
Notice the JsonContent property on URL:
<
personUrl.JsonContent
</syntaxhighlight>
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,785 ⟶ 1,977:
Here’s how we make the previous example work statically:
<
print( person.toStructure( "Person", false ) )
</syntaxhighlight>
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:
<
structure Person {
static function fromJson( jsonText: String ): Person {
Line 1,818 ⟶ 2,010:
}
}
</syntaxhighlight>
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:
<
var person = Person.fromJsonUrl( personUrl )
print( person.Name )
print( person.Address.City )
print( person.Hobby[0].Name )
</syntaxhighlight>
All statically verified and fully code completion friendly!
Other features:
<
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>
And similar to JavaScript, you can directly evaluate a Gosu Expando initializer string:
<
var clone = eval( person.toGosu() )
</syntaxhighlight>
=={{header|Groovy}}==
Line 1,844 ⟶ 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]].
<
def result = slurper.parseText('''
{
Line 1,856 ⟶ 2,048:
]
}
''')</
Test:
<
assert result.people[0].name == [family:'Flintstone', given:'Frederick']
Line 1,866 ⟶ 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']</
{{out}}
Line 1,878 ⟶ 2,070:
=={{header|Halon}}==
<
$sample = ["blue" => [1, 2], "ocean" => "water"];
$jsonstring = json_encode($sample, ["pretty_print" => true]);</
=={{header|Harbour}}==
Parse JSON string into the ''arr'' variable:
<
hb_jsonDecode( '[101,[26,"Test1"],18,false]', @arr )</
{{out}} the JSON representation of an array ''arr'':
<
? hb_jsonEncode( arr )
// The output is:
// [101,[26,"Test1"],18,false]</
=={{header|Haskell}}==
Line 1,897 ⟶ 2,089:
Uses the Aeson library from hackage (http://hackage.haskell.org/package/aeson).
<syntaxhighlight lang="haskell">
{-# LANGUAGE OverloadedStrings #-}
Line 1,923 ⟶ 2,115:
Right v | otherwise -> print v
</syntaxhighlight>
An example using Aeson and TemplateHaskell. Note that it can handle the absence of keys.
<
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
import Data.Aeson
Line 1,943 ⟶ 2,135:
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)
</syntaxhighlight>
An example using Aeson and GHC.Generics. Note that it can handle the absence of keys.
<
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import Data.Aeson
Line 1,964 ⟶ 2,156:
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)
</syntaxhighlight>
=={{header|Hoon}}==
<
|= [^ [in=@tas ~] ~]
:- %noun
Line 1,981 ⟶ 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</
Usage: Put code in gen/json.hoon
Line 1,988 ⟶ 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,993 ⟶ 2,207:
Here is a minimal implementation based on [http://www.jsoftware.com/pipermail/chat/2007-April/000462.html an old email message].
<
NB. 0: whitespace
NB. 1: "
Line 2,042 ⟶ 2,256:
jsonSer0=: '"', jsonEsc@:":, '"'"_
jsonEsc=: rplc&(<;._1' \ \\ " \"')
jsonSerialize=:jsonSer0`jsonSer2@.(*@L.)</
Example use:
<syntaxhighlight lang="text"> jsonParse'{ "blue": [1,2], "ocean": "water" }'
┌────────────────┐
│┌──────┬───────┐│
Line 2,058 ⟶ 2,272:
└──────────────────────────────┘
jsonSerialize jsonParse'{ "blue": [1,2], "ocean": "water" }'
[[["\"blue\"","\"ocean\""],[["1","2"],"\"water\""]]]</
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,066 ⟶ 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.
<
public class JsonExample {
Line 2,108 ⟶ 2,322:
}
}</
=={{header|JavaScript}}==
Requires JSON library, now present in all major browsers.
<
var sample = { "blue": [1,2], "ocean": "water" };
var json_string = JSON.stringify(sample);</
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,121 ⟶ 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
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,127 ⟶ 2,341:
{ "blue": [1,2], "ocean": "water" }
<syntaxhighlight lang
produces:
{"blue":[1,2],"ocean":"water"}
<syntaxhighlight lang
produces:
"{\"blue\":[1,2],\"ocean\":\"water\"}"
=={{header|Jsish}}==
<
Jsish interactive: see 'help [cmd]'
# var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
Line 2,150 ⟶ 2,364:
# puts(JSON.stringify(sample))
{ "blue":[ 1, 2 ], "ocean":"water" }</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
using JSON
Line 2,167 ⟶ 2,381:
@assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}"
@assert jsonobj == Dict("ocean" => "water", "blue" => [1, 2])
@assert typeof(jsonobj) == Dict{String, Any}</
=={{header|Kotlin}}==
We use Kotlin JS here to obtain access to the JavaScript JSON object:
<
data class JsonObject(val foo: Int, val bar: Array<String>)
Line 2,185 ⟶ 2,399:
val data2 = JsonObject2("water", arrayOf(1, 2))
println(JSON.stringify(data2))
}</
{{out}}
Line 2,194 ⟶ 2,408:
=={{header|Lasso}}==
<
local(mymap = map(
'success' = true,
Line 2,228 ⟶ 2,442:
'<br />'
json_deserialize(#myjson) // map(Closed = array(Wednesday, Thursday, Friday), numeric = 11, Open = array(Monday, Tuesday), string = Eleven, success = true)</
=={{header|LFE}}==
Line 2,235 ⟶ 2,449:
===Encoding===
<
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14))
</syntaxhighlight>
The result from that can be made a little more legible with the following:
<
(: erlang binary_to_list
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14)))
</syntaxhighlight>
===Decoding===
We can run the encoding example in reverse, and get back what we put in above with the following:
<
(: jiffy decode '"[1,2,3,[97,112,112,108,101],true,3.14]")
</syntaxhighlight>
Here's a key-value example:
<
(: jiffy decode '"{\"foo\": [1, 2, 3]}")
</syntaxhighlight>
===Decoding to Patterns===
We can also extract the key and value using Erlang patterns:
<
(let (((tuple (list (tuple key value)))
(: jiffy decode '"{\"foo\": [1, 2, 3]}")))
(: io format '"~p: ~p~n" (list key value)))
</syntaxhighlight>
=={{header|Lingo}}==
Line 2,270 ⟶ 2,484:
JavaScript movie script "JSON":
<
// Simple (unsafe) JSON decoder based on eval()
// @param {string} json
Line 2,314 ⟶ 2,528:
return hash[c]
});
}</
Lingo movie script "JSON":<
-- JSON encoder
-- Supported Lingo data types: VOID, integer, float, string, symbol, list, propList
Line 2,365 ⟶ 2,579:
delete the last char of str
return str
end</
Usage:
<
42,\
3.14159,\
Line 2,383 ⟶ 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>]</
=={{header|Lua}}==
Line 2,389 ⟶ 2,603:
Using the [http://www.eharning.us/wiki/luajson/ luajson] library:
<
local json_data = [=[[
Line 2,426 ⟶ 2,640:
}
print("JSON from new Lua data: " .. json.encode(data))</
Since in Lua
To manually insert a <code>null</code> value in the JSON output,
use the <code>json.util.null</code> function.
Line 2,468 ⟶ 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">
MODULE A {
\\ Process data in json format
Line 2,580 ⟶ 2,794:
// call A
A
</syntaxhighlight>
=={{header|Maple}}==
<
[table(["tree" = "maple", "count" = 21])]
> JSON:-ToString( [table(["tree" = "maple", "count" = 21])] );
"[{\"count\": 21, \"tree\": \"maple\"}]"</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"]
ExportString[data, "JSON"]</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
<
ans =
struct with fields:
Line 2,603 ⟶ 2,815:
>> jsonencode(ans)
ans =
{"foo":1,"bar":[10,"apples"]}</
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,609 ⟶ 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.
<
options replace format comments java crossref symbols nobinary
Line 2,746 ⟶ 2,958:
ts.append(']')
return ts.toString()
</syntaxhighlight>
{{out}}
<pre>
Line 2,787 ⟶ 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.
<
options replace format comments java crossref symbols nobinary
Line 2,868 ⟶ 3,080:
ts.append(']')
return ts.toString()
</syntaxhighlight>
{{out}}
<pre>
Line 2,898 ⟶ 3,110:
=={{header|Nim}}==
<
var data = parseJson("""{ "foo": 1, "bar": [10, "apples"] }""")
Line 2,905 ⟶ 3,117:
var js = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}]
echo js</
{{out}}
<pre>1
[
[
=={{header|Objeck}}==
<
use Struct;
use JSON;
Line 2,926 ⟶ 3,138:
}
}
}</
=={{header|Objective-C}}==
{{works with|Mac OS X|10.7+|Xcode 4.4+}}
<
id obj = [NSJSONSerialization
JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding]
Line 2,944 ⟶ 3,156:
encoding: NSUTF8StringEncoding];
NSLog(@"%@", jsonString2);
</syntaxhighlight>
=={{header|OCaml}}==
Line 2,953 ⟶ 3,165:
{{libheader|json-static}}
<
< name "Name": string;
kingdom "Kingdom": string;
Line 2,976 ⟶ 3,188:
let () =
let j = Json_io.json_of_string str in
print_endline (Json_io.string_of_json j);</
compile with:
Line 2,985 ⟶ 3,197:
{{libheader|yojson}}
<
let s = "
Line 3,015 ⟶ 3,227:
let () =
let json = Yojson.Basic.from_string s in
List.iter print_endline (extract_titles json)</
Compile and run:
Line 3,036 ⟶ 3,248:
A Json object can be converted to a string using #asString
<
[1] (Json) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" : 1986 }
ok
Line 3,045 ⟶ 3,257:
[1] (Json) {"parents" : ["Otmar Gutmann", "Silvio Mazzola"], "name" : "Pingu", "born" : 1986 }
ok
></
=={{header|Ol}}==
Ol comes with library that provides JSON parsing and forming.
<
(import (file json))
Line 3,097 ⟶ 3,309:
}
]
</syntaxhighlight>
{{out}}
Line 3,110 ⟶ 3,322:
=={{header|OpenEdge/Progress}}==
The WRITE-JSON and READ-JSON methods were introduced in Progress OpenEdge 10.2B.
<
DEFINE VARIABLE lcjson AS LONGCHAR NO-UNDO.
Line 3,143 ⟶ 3,355:
example.blue [1] example.blue [2] SKIP
example.ocean
VIEW-AS ALERT-BOX.</
{{out}} write-json:
Line 3,180 ⟶ 3,392:
=={{header|Oz}}==
Using the [http://code.google.com/p/oz-code/downloads/list google.com/oz-code] JSON library:
<
[JSON] = {Module.link ['JSON.ozf']}
Line 3,186 ⟶ 3,398:
Sample = object(blue:array(1 2) ocean:"water")
{System.showInfo {JSON.encode Sample}}</
{{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}}
<
my $data = decode_json('{ "foo": 1, "bar": [10, "apples"] }');
my $sample = { blue => [1,2], ocean => "water" };
my $json_string = encode_json($sample);</
=={{header|Phix}}==
The distribution now contains a simple json module
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<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>
<span style="color: #008000;">`1`</span><span style="color: #0000FF;">,</span>
<span style="
<span style="
<span style="
<span style="color: #008000;">`[null,12]`</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">`[
<span style="
<span style="
<span style="
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,254 ⟶ 3,547:
=={{header|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,260 ⟶ 3,553:
$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?></
=={{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.
<
(unless (= X Item)
(quit "Bad JSON" Item) ) )
Line 3,312 ⟶ 3,605:
(and (cdr X) (prin ", ")) )
Item )
(prin "}") ) ) )</
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,331 ⟶ 3,624:
=={{header|Pike}}==
<
// Decoding
string json = "{\"cake\":[\"desu\",1,2.3],\"foo\":1}";
Line 3,343 ⟶ 3,636:
write("%s\n", Standards.JSON.encode(m));
}</
<pre>([ /* 2 elements */
Line 3,357 ⟶ 3,650:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
# JSON input is being stored in ordered hashtable.
# Ordered hashtable is available in PowerShell v3 and higher.
Line 3,365 ⟶ 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>
{{out}}
<syntaxhighlight lang="powershell">
{
"foo": 1,
Line 3,379 ⟶ 3,672:
---- ------------------------ ----
12:25:25 PM 1414326325923 10-26-2014
</syntaxhighlight>
=={{header|Prolog}}==
Line 3,385 ⟶ 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.
<
library(func) ]).
Line 3,406 ⟶ 3,699:
year:1985
}},
json_write(current_output, Dict). %% This accomplishes serializing the JSON object.</
{{out}} from these two example predicates:
<
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,427 ⟶ 3,720:
}
}
true.</
=={{header|PureBasic}}==
<
If CreateJSON(1)
PB_Team_Members=SetJSONObject(JSONValue(1))
Line 3,463 ⟶ 3,756:
PrintN(Mid(PB_Special_thanks$,JSONErrorPosition()+1))
EndIf
Input()</
{{out}}
<pre>PureBasic - Team Members:
Line 3,486 ⟶ 3,779:
=={{header|Python}}==
{{works with|Python|2.6+}}{{works with|Python|3.0+}}
<
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
Line 3,495 ⟶ 3,788:
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}</
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():
<
>>> data = eval('{ "foo": 1, "bar": [10, "apples"] }')
>>> data
{'foo': 1, 'bar': [10, 'apples']}</
=={{header|R}}==
<
data <- fromJSON('{ "foo": 1, "bar": [10, "apples"] }')
data</
<pre>data
$foo
Line 3,518 ⟶ 3,811:
[1] "apples"
</pre>
<syntaxhighlight lang
<pre>{"foo":1,"bar":[10,"apples"]}</pre>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 3,531 ⟶ 3,824:
(write-json '(1 2 "three" #hash((x . 1) (y . 2) (z . 3))))
</syntaxhighlight>
=={{header|Raku}}==
Line 3,538 ⟶ 3,831:
Using [http://github.com/moritz/json/ JSON::Tiny]
<syntaxhighlight lang="raku"
say to-json %( blue => [1,2], ocean => "water" );
</syntaxhighlight>
{{out}}
<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]
<
"id": "file",
"string": "File:",
Line 3,562 ⟶ 3,857:
res: json-to-rebol json-str
js: rebol-to-json res
</syntaxhighlight>
json-to-rebol Result:
Line 3,600 ⟶ 3,895:
=={{header|Ruby}}==
<
ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}')
Line 3,607 ⟶ 3,902:
ruby_obj["ocean"] = { "water" => ["fishy", "salty"] }
puts JSON.generate(ruby_obj)
puts JSON.pretty_generate(ruby_obj)</
{{out}}
Line 3,631 ⟶ 3,926:
{{works with|Rust|1.31}}
{{libheader|Serde|1.0}}
<
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"</
Serde is a general serialization/deserialization library. Serde-JSON implements JSON serialization for Serde.
Line 3,639 ⟶ 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.
<
#[derive(Serialize, Deserialize, Debug)]
Line 3,645 ⟶ 3,940:
x: i32,
y: i32,
}</
Said type could then be used as such:
<
let point = Point { x: 1, y: 2 };
Line 3,657 ⟶ 3,952:
println!("serialized = {}", serialized);
println!("deserialized = {:?}", deserialized);
}</
The result of which is type-checked JSON (where extra entries get ignored), without need of a key-value container.
Line 3,667 ⟶ 3,962:
It also handles more Rust specific types like enums, tuples, struct tuples, and zero-sized types.
<
struct W { a: i32, b: i32 } // => { "a": 0, "b": 0 }
Line 3,685 ⟶ 3,980:
Y(i32), // => { "Y": 0 }
Z, // => { "Z" }
}</
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.
<
use serde_json::Value;
Line 3,698 ⟶ 3,993:
#[serde(flatten)]
metadata: HashMap<String, Value>,
}</
In this example <code>metadata</code> would simply capture all other additional entries, for example:
<
let data = {
let mut metadata = HashMap::new();
Line 3,719 ⟶ 4,014:
println!("serialized = {}", serialized);
println!("deserialized = {:?}", deserialized);
}</
{{out}}
<pre>serialized = {"points":[{"x":1,"y":2},{"x":15,"y":32}],"square":false,"triangle":3}
Line 3,728 ⟶ 4,023:
Using the builtin parsing lib (debatably slower than third-party libs such as lift-json from Liftweb).
<
import scala.util.parsing.json.{JSON, JSONObject}
Line 3,736 ⟶ 4,031:
scala> JSONObject(Map("foo" -> "bar")).toString()
res1: String = {"foo" : "bar"}
</syntaxhighlight>
=={{header|Scheme}}==
{{works with|Chicken Scheme}}
Using the [http://api.call-cc.org/doc/json json] egg: <
(use json)
(define object-example
Line 3,753 ⟶ 4,048:
; this writes the following:
; {"foo": "bar", "baz": [1, 2, 3], "qux": {"foo": "bar"}}
</syntaxhighlight>
=={{header|SenseTalk}}==
<
put JSONValue(jsonString)
set dataObject to (string_value: "lorem ipsum", int_value: 314, array_value: (2, 4, 6))
put JSONFormat(dataObject)</
=={{header|Sidef}}==
<
var data = json.decode('{"blue": [1, 2], "ocean": "water"}')
say data
data{:ocean} = Hash
say json.encode(data)
{{out}}
<pre>Hash
)
{"blue":[1,2],"ocean":{"water":["fishy","salty"]}}</pre>
=={{header|Smalltalk}}==
Use the NeoJSON library: [http://smalltalkhub.com/#!/~SvenVanCaekenberghe/Neo NeoJSON]
<
NeoJSONReader fromString: '{ "foo": 1, "bar": [10, "apples"] }'.
</syntaxhighlight>
{{out}}
Line 3,788 ⟶ 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">
val Validate = fn jsonstring =>
let
Line 3,917 ⟶ 4,212:
end ;
</
<syntaxhighlight 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,948 ⟶ 4,243:
elem (St "postalCode", value (St "10021"))]):
(jvals, jvals content) element
</syntaxhighlight>
=={{header|Swift}}==
<
let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
Line 3,969 ⟶ 4,264:
print("JSON: \(jsonString2)")
}
}</
{{out}}
<pre>
Line 3,990 ⟶ 4,285:
=={{header|Tailspin}}==
A JSON parser and printer can fairly easily be created
<
// 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 4,056 ⟶ 4,351:
when <{}> do
[ $... ] -> '{$(1) -> printKeyValue;$(2..last)... -> ', $ -> printKeyValue;';}' !
when <
'$;'!
when <'
[ $... -> encodeChars ] -> '"$...;"' !
otherwise 'WTF!' !
Line 4,069 ⟶ 4,364:
{ blue: [1,2], ocean: 'water' } -> printJson -> '$;
' -> !OUT::write
'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):
<
set sample {{ "foo": 1, "bar": [10, "apples"] }}
set parsed [json::json2dict $sample]
puts $parsed</
{{out}}
<pre>foo 1 bar {10 apples}</pre>
Line 4,089 ⟶ 4,389:
{{works with|Tcl|8.6}}
{{tcllib|json::write}}
<
package require json::write
Line 4,130 ⟶ 4,430:
}
}
}</
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):
<
puts [tcl2json $d]</
{{out}}
<pre>
Line 4,145 ⟶ 4,445:
=={{header|TXR}}==
===
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.
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,155 ⟶ 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>&#xABCD;</code> and then the filter will produce the proper Unicode character. Similarly \" is translated to <code>&quot;</code> and \n is translated to 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.
<
@(cases)@\
@(string v)@(or)@(num v)@(or)@(object v)@(or)@\
Line 4,215 ⟶ 4,620:
@(end)
@(freeform)
@(maybe)@(value v)@(end)@badsyntax</
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>.
<
(v "O" ((("S" "a") ("O" ((("S" "b") ("N" "3")) (("S" "c") ("A" (("N" "1") ("N" "2") ("N" "3")))))))))
(badsyntax . "[\n")
Line 4,225 ⟶ 4,630:
$ echo -n '"\u1234"' | ./txr -l json.txr -
(v "S" "\11064")
(badsyntax . "")</
=={{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}}
<
var s = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"
Line 4,237 ⟶ 4,683:
o = { "blue": [1, 2], "ocean": "water" }
s = JSON.stringify(o)
System.print(s)</
{{out}}
Line 4,248 ⟶ 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.
<
let $json := '
{
Line 4,278 ⟶ 4,724:
)
</syntaxhighlight>
Result:
Line 4,341 ⟶ 4,787:
To convert from JSON to zkl:
<
var [const] YAJL=a, toJSON=b;
src:=
Line 4,359 ⟶ 4,805:
obj:=YAJL().write(src).close();
// or obj:=src.pump(YAJL()).close(); // for example, from file or socket
obj.println();</
{{out}}
<pre>
Line 4,365 ⟶ 4,811:
</pre>
From zkl to JSON:
<
toJSON(obj).println();</
{{out}}
<pre>{"pi":3.1400000000,"an array":[-1,true,false,null,"foo"],"large number":123456789123456791}
|