JSON: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Tailspin}}: Update to stricter typing) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 7:
=={{header|11l}}==
<
String firstName, lastName
Int age
Line 39:
p.children.append(‘Alex’)
print(json:from_object(p))</
{{out}}
Line 80:
=={{header|Ada}}==
=== Alternative using GNATCOLL ===
<
with Ada.Text_IO;
with GNATCOLL.JSON;
Line 122:
Put_Line (Penguin.Write);
end JSON_Test;
</syntaxhighlight>
{{out}}
Line 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 174:
Put_Line (To_JSON_Document (Penguin).To_JSON.To_Wide_Wide_String);
end Main;
</syntaxhighlight>
{{out}}
Line 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 199:
===Java===
<
// Parse JSON
//
Line 223:
| array;
array : '[' {System.out.println(Indent + "Array"); Indent += " ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};
</syntaxhighlight>
Produces:
<pre>
Line 262:
=={{header|Apex}}==
JSON serialization and deserialization is built in
<
String foo {get;set;}
Integer bar {get;set;}
Line 276:
//"testObj.foo == deserializedObject.foo" is true
//"testObj.bar == deserializedObject.bar" is true
</syntaxhighlight>
=={{header|Arturo}}==
<
object: #[
Line 293:
]
print write.json ø object</
{{out}}
Line 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 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.
Line 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 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 682:
return EXIT_SUCCESS;
}</
{{out}}
Line 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 737:
Console.WriteLine(array[1]);
}
}</
=={{header|C++}}==
Line 743:
{{libheader|U++}}
<
using namespace Upp;
Line 757:
Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}
</syntaxhighlight>
C++11 {{libheader|nlohmann::json}}
<
#include <iomanip> // std::setw
#include <sstream>
Line 825:
return 0;
}
</syntaxhighlight>
=={{header|Caché ObjectScript}}==
<
Class Sample.JSON [ Abstract ]
{
Line 840:
}
</syntaxhighlight>
{{out|Examples}}
<pre>
Line 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 901:
; Pretty-print the Clojure representation of JSON. We've come full circle.
(pprint-json json-map)</
=={{header|CoffeeScript}}==
<
sample =
blue: [1, 2]
Line 914:
console.log json_string
console.log json_obj
</syntaxhighlight>
=={{header|ColdFusion}}==
<
<!--- Create sample JSON structure --->
<cfset json = {
Line 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 953:
(json:decode-json s)))
</syntaxhighlight>
<pre>To load "cl-json":
Line 966:
=={{header|Crystal}}==
Before 1.0.0:
<syntaxhighlight lang="ruby">
require "json_mapping"
Line 981:
puts(foo.to_json)
end
</syntaxhighlight>
After 1.0.0:
<syntaxhighlight lang="ruby">
require "json"
Line 999:
puts(foo.to_json)
end
</syntaxhighlight>
Output:
Line 1,006:
=={{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 1,045:
assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}
</syntaxhighlight>
{{out}}
Line 1,055:
{{trans|JavaScript}}
<
main(){
Line 1,064:
var json_string = jsonEncode(sample);
}
</syntaxhighlight>
=={{header|Delphi}}==
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program JsonTest;
Line 1,123:
Readln;
end.
</syntaxhighlight>
{{out}}
Line 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,170:
→ # (simon 🎩)
</syntaxhighlight>
Line 1,177:
Structures used both to construct and to parse JSON strings:
<
person person;
relationships relationship[]?;
Line 1,191:
relationshipType string;
id int;
end</
Construct JSON string:
<
people.appendElement(new Person { firstName = "Frederick", lastName = "Flintstone", age = 35} );
Line 1,215:
// Show JSON string
SysLib.writeStdout(jsonString);</
{{out|Raw Output}}
Line 1,250:
Parse JSON:
<
family Dictionary;
jsonLib.convertFromJSON(jsonString, family);
Line 1,274:
end
end</
{{out}}
Line 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,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,332:
console.printLine("json.foo=",o.foo);
console.printLine("json.bar=",o.bar)
}</
{{out}}
<pre>
Line 1,345:
Emacs 27.1 offers native JSON processing using the Jansson library.
<
(cl-assert (fboundp 'json-parse-string))
Line 1,362:
;; encoding
(json-serialize example-object) ;=> "{\"foo\":\"bar\",\"baz\":[1,2,3]}"</
{{libheader|json.el}}
<
(defvar example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
Line 1,384:
;; pretty-printing
(let ((json-encoding-pretty-print t))
(message "%s" (json-encode example-object)))</
{{out}}
Line 1,399:
=={{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,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,463:
1. Using Json.Net
<
open Newtonsoft.Json
type Person = {ID: int; Name:string}
Line 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,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,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,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,534:
! Create a new data structure and serialize into JSON
{ { "blue" { "ocean" "water" } } >json
</syntaxhighlight>
=={{header|Fantom}}==
<
using util
Line 1,557:
}
}
</syntaxhighlight>
{{out}}
Line 1,628:
</pre>
<
program json_fortran
use json_module
Line 1,677:
end program json_fortran
</syntaxhighlight>
=={{header|FunL}}==
Line 1,684:
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,708:
=={{header|FutureBasic}}==
FB has dedicated JSON functions making easy to serialize objects as JSON and to convert JSON to objects.
<
include "NSLog.incl"
Line 1,730:
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Line 1,750:
=={{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,774:
fmt.Println(err)
}
}</
{{out}}
<pre>
Line 1,781:
</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,839:
fmt.Println(string(jData))
}
}</
{{out}}
<pre>
Line 1,871:
=={{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,879:
Sample Person JSON (from http://gosu-lang.github.io/data/person.json):
<
"Name": "Dickson Yamada",
"Age": 39,
Line 1,899:
]
}
</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,915:
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,948:
}
}
</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,974:
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,986:
]
}
''')</
Test:
<
assert result.people[0].name == [family:'Flintstone', given:'Frederick']
Line 1,996:
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 2,008:
=={{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 2,027:
Uses the Aeson library from hackage (http://hackage.haskell.org/package/aeson).
<syntaxhighlight lang="haskell">
{-# LANGUAGE OverloadedStrings #-}
Line 2,053:
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 2,073:
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 2,094:
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)
</syntaxhighlight>
=={{header|Hoon}}==
<
|= [^ [in=@tas ~] ~]
:- %noun
Line 2,111:
=. 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 2,123:
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,172:
jsonSer0=: '"', jsonEsc@:":, '"'"_
jsonEsc=: rplc&(<;._1' \ \\ " \"')
jsonSerialize=:jsonSer0`jsonSer2@.(*@L.)</
Example use:
<syntaxhighlight lang="text"> jsonParse'{ "blue": [1,2], "ocean": "water" }'
┌────────────────┐
│┌──────┬───────┐│
Line 2,188:
└──────────────────────────────┘
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,196:
=={{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,238:
}
}</
=={{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,251:
=={{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,257:
{ "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,280:
# puts(JSON.stringify(sample))
{ "blue":[ 1, 2 ], "ocean":"water" }</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
using JSON
Line 2,297:
@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,315:
val data2 = JsonObject2("water", arrayOf(1, 2))
println(JSON.stringify(data2))
}</
{{out}}
Line 2,324:
=={{header|Lasso}}==
<
local(mymap = map(
'success' = true,
Line 2,358:
'<br />'
json_deserialize(#myjson) // map(Closed = array(Wednesday, Thursday, Friday), numeric = 11, Open = array(Monday, Tuesday), string = Eleven, success = true)</
=={{header|LFE}}==
Line 2,365:
===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,400:
JavaScript movie script "JSON":
<
// Simple (unsafe) JSON decoder based on eval()
// @param {string} json
Line 2,444:
return hash[c]
});
}</
Lingo movie script "JSON":<
-- JSON encoder
-- Supported Lingo data types: VOID, integer, float, string, symbol, list, propList
Line 2,495:
delete the last char of str
return str
end</
Usage:
<
42,\
3.14159,\
Line 2,513:
-- [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,519:
Using the [http://www.eharning.us/wiki/luajson/ luajson] library:
<
local json_data = [=[[
Line 2,556:
}
print("JSON from new Lua data: " .. json.encode(data))</
Since in Lua, a variable or table entry with <code>nil</code> is treated as the same as an undefined variable or non-existing table entry, a <code>null</code> value in JSON is decoded to a special function value, which ensures that it can be re-encoded properly to <code>null</code> again.
Line 2,598:
=={{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,710:
// 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}}==
<
ExportString[data, "JSON"]</
=={{header|MATLAB}} / {{header|Octave}}==
<
ans =
struct with fields:
Line 2,731:
>> 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,737:
===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,874:
ts.append(']')
return ts.toString()
</syntaxhighlight>
{{out}}
<pre>
Line 2,915:
===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,996:
ts.append(']')
return ts.toString()
</syntaxhighlight>
{{out}}
<pre>
Line 3,026:
=={{header|Nim}}==
<
var data = parseJson("""{ "foo": 1, "bar": [10, "apples"] }""")
Line 3,033:
var js = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}]
echo js</
{{out}}
<pre>1
Line 3,040:
=={{header|Objeck}}==
<
use Struct;
use JSON;
Line 3,054:
}
}
}</
=={{header|Objective-C}}==
{{works with|Mac OS X|10.7+|Xcode 4.4+}}
<
id obj = [NSJSONSerialization
JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding]
Line 3,072:
encoding: NSUTF8StringEncoding];
NSLog(@"%@", jsonString2);
</syntaxhighlight>
=={{header|OCaml}}==
Line 3,081:
{{libheader|json-static}}
<
< name "Name": string;
kingdom "Kingdom": string;
Line 3,104:
let () =
let j = Json_io.json_of_string str in
print_endline (Json_io.string_of_json j);</
compile with:
Line 3,113:
{{libheader|yojson}}
<
let s = "
Line 3,143:
let () =
let json = Yojson.Basic.from_string s in
List.iter print_endline (extract_titles json)</
Compile and run:
Line 3,164:
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,173:
[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,225:
}
]
</syntaxhighlight>
{{out}}
Line 3,238:
=={{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,271:
example.blue [1] example.blue [2] SKIP
example.ocean
VIEW-AS ALERT-BOX.</
{{out}} write-json:
Line 3,308:
=={{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,314:
Sample = object(blue:array(1 2) ocean:"water")
{System.showInfo {JSON.encode Sample}}</
{{out}}
Line 3,322:
=={{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
<!--<
<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>
Line 3,355:
<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>
<!--</
{{out}}
<pre>
Line 3,382:
=={{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,388:
$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,440:
(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,459:
=={{header|Pike}}==
<
// Decoding
string json = "{\"cake\":[\"desu\",1,2.3],\"foo\":1}";
Line 3,471:
write("%s\n", Standards.JSON.encode(m));
}</
<pre>([ /* 2 elements */
Line 3,485:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
# JSON input is being stored in ordered hashtable.
# Ordered hashtable is available in PowerShell v3 and higher.
Line 3,493:
# 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,507:
---- ------------------------ ----
12:25:25 PM 1414326325923 10-26-2014
</syntaxhighlight>
=={{header|Prolog}}==
Line 3,513:
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,534:
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,555:
}
}
true.</
=={{header|PureBasic}}==
<
If CreateJSON(1)
PB_Team_Members=SetJSONObject(JSONValue(1))
Line 3,591:
PrintN(Mid(PB_Special_thanks$,JSONErrorPosition()+1))
EndIf
Input()</
{{out}}
<pre>PureBasic - Team Members:
Line 3,614:
=={{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,623:
{'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,646:
[1] "apples"
</pre>
<syntaxhighlight lang
<pre>{"foo":1,"bar":[10,"apples"]}</pre>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 3,659:
(write-json '(1 2 "three" #hash((x . 1) (y . 2) (z . 3))))
</syntaxhighlight>
=={{header|Raku}}==
Line 3,666:
Using [http://github.com/moritz/json/ JSON::Tiny]
<syntaxhighlight lang="raku"
my $data = from-json('{ "foo": 1, "bar": [10, "apples"] }');
my $sample = { blue => [1,2], ocean => "water" };
my $json_string = to-json($sample);</
=={{header|REBOL}}==
Using [http://www.json.org/json.r json.org/json.r]
<
"id": "file",
"string": "File:",
Line 3,690:
res: json-to-rebol json-str
js: rebol-to-json res
</syntaxhighlight>
json-to-rebol Result:
Line 3,728:
=={{header|Ruby}}==
<
ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}')
Line 3,735:
ruby_obj["ocean"] = { "water" => ["fishy", "salty"] }
puts JSON.generate(ruby_obj)
puts JSON.pretty_generate(ruby_obj)</
{{out}}
Line 3,759:
{{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,767:
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,773:
x: i32,
y: i32,
}</
Said type could then be used as such:
<
let point = Point { x: 1, y: 2 };
Line 3,785:
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,795:
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,813:
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,826:
#[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,847:
println!("serialized = {}", serialized);
println!("deserialized = {:?}", deserialized);
}</
{{out}}
<pre>serialized = {"points":[{"x":1,"y":2},{"x":15,"y":32}],"square":false,"triangle":3}
Line 3,856:
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,864:
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,881:
; 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.new(water => %w[fishy salty]);
say json.encode(data);</
{{out}}
<pre>Hash.new(
Line 3,905:
=={{header|Smalltalk}}==
Use the NeoJSON library: [http://smalltalkhub.com/#!/~SvenVanCaekenberghe/Neo NeoJSON]
<
NeoJSONReader fromString: '{ "foo": 1, "bar": [10, "apples"] }'.
</syntaxhighlight>
{{out}}
Line 3,916:
=={{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 4,045:
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 4,076:
elem (St "postalCode", value (St "10021"))]):
(jvals, jvals content) element
</syntaxhighlight>
=={{header|Swift}}==
<
let jsonString = "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"
Line 4,097:
print("JSON: \(jsonString2)")
}
}</
{{out}}
<pre>
Line 4,118:
=={{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,201:
' -> printJson -> '$;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 4,211:
=={{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,222:
{{works with|Tcl|8.6}}
{{tcllib|json::write}}
<
package require json::write
Line 4,263:
}
}
}</
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,292:
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,348:
@(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,358:
$ echo -n '"\u1234"' | ./txr -l json.txr -
(v "S" "\11064")
(badsyntax . "")</
=={{header|Vlang}}==
<
struct User {
Line 4,387:
println(json.encode(user))
}</
{{out}}
Line 4,403:
=={{header|Wren}}==
{{libheader|Wren-json}}
<
var s = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }"
Line 4,411:
o = { "blue": [1, 2], "ocean": "water" }
s = JSON.stringify(o)
System.print(s)</
{{out}}
Line 4,422:
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,452:
)
</syntaxhighlight>
Result:
Line 4,515:
To convert from JSON to zkl:
<
var [const] YAJL=a, toJSON=b;
src:=
Line 4,533:
obj:=YAJL().write(src).close();
// or obj:=src.pump(YAJL()).close(); // for example, from file or socket
obj.println();</
{{out}}
<pre>
Line 4,539:
</pre>
From zkl to JSON:
<
toJSON(obj).println();</
{{out}}
<pre>{"pi":3.1400000000,"an array":[-1,true,false,null,"foo"],"large number":123456789123456791}
|