Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

2
Task/JSON/00-META.yaml Normal file
View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/JSON

6
Task/JSON/00-TASK.txt Normal file
View file

@ -0,0 +1,6 @@
Load a [[wp:JSON|JSON]] string into a data structure.
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).

33
Task/JSON/11l/json.11l Normal file
View file

@ -0,0 +1,33 @@
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))

1
Task/JSON/ANT/json.ant Normal file
View file

@ -0,0 +1 @@
json:{[data]catch[eval[,|{[y]catch[{":" = "="; "[" = "<"; "]" = ">"; "," = ";"}[y];{x};{[]y}]}'("""("(\\.|[^\\"])*"|\-?[0-9]+(\.[0-9]+)?|\{|\}|\[|\]|\:|\,)"""~data)["strings"]];{x};{error["Invalid JSON"]}]}

View file

@ -0,0 +1,23 @@
// Parse JSON
//
// Nigel Galloway - April 27th., 2012
//
grammar JSON ;
@members {
String Indent = "";
}
Number : (('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS : (' ' | '\t' | '\r' |'\n') {skip();};
Tz : ' ' .. '!' | '#' .. '[' | ']' .. '~';
Control : '\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode : 'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword : 'true' | 'false' | 'null';
String : '"' (Control? Tz)* '"';
object : '{' {System.out.println(Indent + "{Object}"); Indent += " ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair : e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value : Number {System.out.println(Indent + "{Number} \t" + $Number.text);}
| object
| String {System.out.println(Indent + "{String} \t" + $String.text);}
| Keyword {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
| array;
array : '[' {System.out.println(Indent + "Array"); Indent += " ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};

41
Task/JSON/Ada/json-1.ada Normal file
View file

@ -0,0 +1,41 @@
with Ada.Text_IO;
with GNATCOLL.JSON;
procedure JSON_Test is
use Ada.Text_IO;
use GNATCOLL.JSON;
JSON_String : constant String := "{""name"":""Pingu"",""born"":1986}";
Penguin : JSON_Value := Create_Object;
Parents : JSON_Array;
begin
Penguin.Set_Field (Field_Name => "name",
Field => "Linux");
Penguin.Set_Field (Field_Name => "born",
Field => 1992);
Append (Parents, Create ("Linus Torvalds"));
Append (Parents, Create ("Alan Cox"));
Append (Parents, Create ("Greg Kroah-Hartman"));
Penguin.Set_Field (Field_Name => "parents",
Field => Parents);
Put_Line (Penguin.Write);
Penguin := Read (JSON_String, "json.errors");
Penguin.Set_Field (Field_Name => "born",
Field => 1986);
Parents := Empty_Array;
Append (Parents, Create ("Otmar Gutmann"));
Append (Parents, Create ("Silvio Mazzola"));
Penguin.Set_Field (Field_Name => "parents",
Field => Parents);
Put_Line (Penguin.Write);
end JSON_Test;

41
Task/JSON/Ada/json-2.ada Normal file
View file

@ -0,0 +1,41 @@
with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO;
with League.JSON.Arrays; use League.JSON.Arrays;
with League.JSON.Documents; use League.JSON.Documents;
with League.JSON.Objects; use League.JSON.Objects;
with League.JSON.Values; use League.JSON.Values;
with League.Strings; use League.Strings;
procedure Main is
function "+" (Item : Wide_Wide_String) return Universal_String
renames To_Universal_String;
JSON_String : constant Universal_String
:= +"{""name"":""Pingu"",""born"":1986}";
Penguin : JSON_Object;
Parents : JSON_Array;
begin
Penguin.Insert (+"name", To_JSON_Value (+"Linux"));
Penguin.Insert (+"born", To_JSON_Value (1992));
Parents.Append (To_JSON_Value (+"Linus Torvalds"));
Parents.Append (To_JSON_Value (+"Alan Cox"));
Parents.Append (To_JSON_Value (+"Greg Kroah-Hartman"));
Penguin.Insert (+"parents", To_JSON_Value (Parents));
Put_Line (To_JSON_Document (Penguin).To_JSON.To_Wide_Wide_String);
Penguin := From_JSON (JSON_String).To_JSON_Object;
Parents := Empty_JSON_Array;
Parents.Append (To_JSON_Value (+"Otmar Gutmann"));
Parents.Append (To_JSON_Value (+"Silvio Mazzola"));
Penguin.Insert (+"parents", To_JSON_Value (Parents));
Put_Line (To_JSON_Document (Penguin).To_JSON.To_Wide_Wide_String);
end Main;

14
Task/JSON/Apex/json.apex Normal file
View file

@ -0,0 +1,14 @@
class TestClass{
String foo {get;set;}
Integer bar {get;set;}
}
TestClass testObj = new TestClass();
testObj.foo = 'ABC';
testObj.bar = 123;
String serializedString = JSON.serialize(testObj);
TestClass deserializedObject = (TestClass)JSON.deserialize(serializedString, TestClass.class);
//"testObj.foo == deserializedObject.foo" is true
//"testObj.bar == deserializedObject.bar" is true

View file

@ -0,0 +1,14 @@
print read.json {{ "foo": 1, "bar": [10, "apples"] }}
object: #[
name: "john"
surname: "doe"
address: #[
number: 10
street: "unknown"
country: "Spain"
]
married: false
]
print write.json ø object

View file

@ -0,0 +1 @@
put$(jsn$(get$("input.json",JSN)),"output.JSN,NEW)

View file

@ -0,0 +1 @@
get$("myfile.json",JSN)

View file

@ -0,0 +1 @@
get$("[1,2,3]",JSN,MEM)

View file

@ -0,0 +1 @@
jsn$(,1 2 3)

View file

@ -0,0 +1 @@
put$("[1,2,3]","array.json",NEW)

View file

@ -0,0 +1,4 @@
( get$("rosetta.json",JSN):?json
& lst$(json,"json.bra",NEW)
& put$(jsn$!json,"rosetta-roundtrip.json",NEW)
)

14
Task/JSON/C++/json-1.cpp Normal file
View file

@ -0,0 +1,14 @@
#include "Core/Core.h"
using namespace Upp;
CONSOLE_APP_MAIN
{
JsonArray a;
a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321");
String txt = ~a;
Cout() << txt << '\n';
Value v = ParseJSON(txt);
for(int i = 0; i < v.GetCount(); i++)
Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}

65
Task/JSON/C++/json-2.cpp Normal file
View file

@ -0,0 +1,65 @@
#include <iostream>
#include <iomanip> // std::setw
#include <sstream>
#include <cassert>
#include "json.hpp"
using json = nlohmann::json;
int main( int argc, char* argv[] )
{
std::string const expected =
R"delim123({
"answer": {
"everything": 42
},
"happy": true,
"list": [
1,
0,
2
],
"name": "Niels",
"nothing": null,
"object": {
"currency": "USD",
"value": 42.99
},
"pi": 3.141
})delim123";
json const jexpected = json::parse( expected );
assert( jexpected["list"][1].get<int>() == 0 );
assert( jexpected["object"]["currency"] == "USD" );
json jhandmade = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}
},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}
}
};
assert( jexpected == jhandmade );
std::stringstream jhandmade_stream;
jhandmade_stream << std::setw(4) << jhandmade;
std::string jhandmade_string = jhandmade.dump(4);
assert( jhandmade_string == expected );
assert( jhandmade_stream.str() == expected );
return 0;
}

23
Task/JSON/C-sharp/json.cs Normal file
View file

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
class Program
{
static void Main()
{
var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(people);
Console.WriteLine(json);
var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
Console.WriteLine(deserialized["2"]);
var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
var data = jsonObject as Dictionary<string, object>;
var array = data["bar"] as object[];
Console.WriteLine(array[1]);
}
}

120
Task/JSON/C/json.c Normal file
View file

@ -0,0 +1,120 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yajl/yajl_tree.h>
#include <yajl/yajl_gen.h>
static void print_callback (void *ctx, const char *str, size_t len)
{
FILE *f = (FILE *) ctx;
fwrite (str, 1, len, f);
}
static void check_status (yajl_gen_status status)
{
if (status != yajl_gen_status_ok)
{
fprintf (stderr, "yajl_gen_status was %d\n", (int) status);
exit (EXIT_FAILURE);
}
}
static void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)
{
size_t i;
switch (val->type)
{
case yajl_t_string:
check_status (yajl_gen_string (gen,
(const unsigned char *) val->u.string,
strlen (val->u.string)));
break;
case yajl_t_number:
if (parse_numbers && YAJL_IS_INTEGER (val))
check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));
else if (parse_numbers && YAJL_IS_DOUBLE (val))
check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));
else
check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),
strlen (YAJL_GET_NUMBER (val))));
break;
case yajl_t_object:
check_status (yajl_gen_map_open (gen));
for (i = 0 ; i < val->u.object.len ; i++)
{
check_status (yajl_gen_string (gen,
(const unsigned char *) val->u.object.keys[i],
strlen (val->u.object.keys[i])));
serialize_value (gen, val->u.object.values[i], parse_numbers);
}
check_status (yajl_gen_map_close (gen));
break;
case yajl_t_array:
check_status (yajl_gen_array_open (gen));
for (i = 0 ; i < val->u.array.len ; i++)
serialize_value (gen, val->u.array.values[i], parse_numbers);
check_status (yajl_gen_array_close (gen));
break;
case yajl_t_true:
check_status (yajl_gen_bool (gen, 1));
break;
case yajl_t_false:
check_status (yajl_gen_bool (gen, 0));
break;
case yajl_t_null:
check_status (yajl_gen_null (gen));
break;
default:
fprintf (stderr, "unexpectedly got type %d\n", (int) val->type);
exit (EXIT_FAILURE);
}
}
static void print_tree (FILE *f, yajl_val tree, int parse_numbers)
{
yajl_gen gen;
gen = yajl_gen_alloc (NULL);
if (! gen)
{
fprintf (stderr, "yajl_gen_alloc failed\n");
exit (EXIT_FAILURE);
}
if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1) ||
0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1) ||
0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))
{
fprintf (stderr, "yajl_gen_config failed\n");
exit (EXIT_FAILURE);
}
serialize_value (gen, tree, parse_numbers);
yajl_gen_free (gen);
}
int main (int argc, char **argv)
{
char err_buf[200];
const char *json =
"{\"pi\": 3.14, \"large number\": 123456789123456789123456789, "
"\"an array\": [-1, true, false, null, \"foo\"]}";
yajl_val tree;
tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));
if (! tree)
{
fprintf (stderr, "parsing failed because: %s\n", err_buf);
return EXIT_FAILURE;
}
printf ("Treating numbers as strings...\n");
print_tree (stdout, tree, 0);
printf ("Parsing numbers to long long or double...\n");
print_tree (stdout, tree, 1);
yajl_tree_free (tree);
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,10 @@
(use 'clojure.data.json)
; Load as Clojure data structures and bind the resulting structure to 'json-map'.
(def json-map (read-json "{ \"foo\": 1, \"bar\": [10, \"apples\"] }"))
; Use pr-str to print out the Clojure representation of the JSON created by read-json.
(pr-str json-map)
; Pretty-print the Clojure representation of JSON. We've come full circle.
(pprint-json json-map)

View file

@ -0,0 +1,9 @@
sample =
blue: [1, 2]
ocean: 'water'
json_string = JSON.stringify sample
json_obj = JSON.parse json_string
console.log json_string
console.log json_obj

View file

@ -0,0 +1,20 @@
<!--- Create sample JSON structure --->
<cfset json = {
string: "Hello",
number: 42,
arrayOfNumbers: [1, 2, 3, 4],
arrayOfStrings: ["One", "Two", "Three", "Four"],
arrayOfAnything: [1, "One", [1, "One"], { one: 1 }],
object: {
key: "value"
}
} />
<!--- Convert to JSON string --->
<cfset jsonSerialized = serializeJSON(json) />
<!--- Convert back to ColdFusion --->
<cfset jsonDeserialized = deserializeJSON(jsonSerialized) />
<!--- Output examples --->
<cfdump var="#jsonSerialized#" />
<cfdump var="#jsonDeserialized#" />

View file

@ -0,0 +1,9 @@
(ql:quickload '("cl-json"))
(json:encode-json
'#( ((foo . (1 2 3)) (bar . t) (baz . #\!))
"quux" 4/17 4.25))
(print (with-input-from-string
(s "{\"foo\": [1, 2, 3], \"bar\": true, \"baz\": \"!\"}")
(json:decode-json s)))

View file

@ -0,0 +1,14 @@
require "json_mapping"
class Foo
JSON.mapping(
num: Int64,
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

View file

@ -0,0 +1,14 @@
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

6
Task/JSON/D/json.d Normal file
View file

@ -0,0 +1,6 @@
import std.stdio, std.json;
void main() {
auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`);
writeln(toJSON(&j));
}

View file

@ -0,0 +1,30 @@
import 'dart:convert' show jsonDecode, jsonEncode;
main(){
var json_string = '''
{
"rosetta_code": {
"task": "json",
"language": "dart",
"descriptions": [ "fun!", "easy to learn!", "awesome!" ]
}
}
''';
// decode string into Map<String, dynamic>
var json_object = jsonDecode(json_string);
for ( var description in json_object["rosetta_code"]["descriptions"] )
print( "dart is $description" );
var dart = {
"compiled": true,
"interpreted": true,
"creator(s)":[ "Lars Bak", "Kasper Lund"],
"development company": "Google"
};
var as_json_text = jsonEncode(dart);
assert(as_json_text == '{"compiled":true,"interpreted":true,"creator(s)":["Lars Bak","Kasper Lund"],"development company":"Google"}');
}

View file

@ -0,0 +1,9 @@
import 'dart:convert';
main(){
var data = jsonDecode('{ "foo": 1, "bar": [10, "apples"] }');
var sample = { "blue": [1,2], "ocean": "water" };
var json_string = jsonEncode(sample);
}

View file

@ -0,0 +1,55 @@
program JsonTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Json;
type
TJsonObjectHelper = class helper for TJsonObject
public
class function Deserialize(data: string): TJsonObject; static;
function Serialize: string;
end;
{ TJsonObjectHelper }
class function TJsonObjectHelper.Deserialize(data: string): TJsonObject;
begin
Result := TJSONObject.ParseJSONValue(data) as TJsonObject;
end;
function TJsonObjectHelper.Serialize: string;
begin
Result := ToJson;
end;
var
people, deserialized: TJsonObject;
bar: TJsonArray;
_json: string;
begin
people := TJsonObject.Create();
people.AddPair(TJsonPair.Create('1', 'John'));
people.AddPair(TJsonPair.Create('2', 'Susan'));
_json := people.Serialize;
Writeln(_json);
deserialized := TJSONObject.Deserialize(_json);
Writeln(deserialized.Values['2'].Value);
deserialized := TJSONObject.Deserialize('{"foo":1 , "bar":[10,"apples"]}');
bar := deserialized.Values['bar'] as TJSONArray;
Writeln(bar.Items[1].Value);
deserialized.Free;
people.Free;
Readln;
end.

15
Task/JSON/EGL/json-1.egl Normal file
View file

@ -0,0 +1,15 @@
record familyMember
person person;
relationships relationship[]?;
end
record person
firstName string;
lastName string;
age int;
end
record relationship
relationshipType string;
id int;
end

22
Task/JSON/EGL/json-2.egl Normal file
View file

@ -0,0 +1,22 @@
people Person[]; // Array of people
people.appendElement(new Person { firstName = "Frederick", lastName = "Flintstone", age = 35} );
people.appendElement(new Person { firstName = "Wilma", lastName = "Flintstone", age = 34} );
people.appendElement(new Person { firstName = "Pebbles", lastName = "Flintstone", age = 2} );
people.appendElement(new Person { firstName = "Bernard", lastName = "Rubble", age = 32} );
people.appendElement(new Person { firstName = "Elizabeth", lastName = "Rubble", age = 29} );
people.appendElement(new Person { firstName = "Bam Bam", lastName = "Rubble", age = 2} );
family Dictionary; // A dictionary of family members using a uid as key
family["1"] = new FamilyMember{ person = people[1], relationships = [new Relationship{ relationshipType="spouse", id = 2 }, new Relationship{ relationshipType="child", id = 3}] };
family["2"] = new FamilyMember{ person = people[2], relationships = [new Relationship{ relationshipType="spouse", id = 1 }, new Relationship{ relationshipType="child", id = 3}] };
family["3"] = new FamilyMember{ person = people[3], relationships = [new Relationship{ relationshipType="mother", id = 2 }, new Relationship{ relationshipType="father", id = 1}] };
family["4"] = new FamilyMember{ person = people[4], relationships = [new Relationship{ relationshipType="spouse", id = 5 }, new Relationship{ relationshipType="child", id = 6}] };
family["5"] = new FamilyMember{ person = people[5], relationships = [new Relationship{ relationshipType="spouse", id = 4 }, new Relationship{ relationshipType="child", id = 6}] };
family["6"] = new FamilyMember{ person = people[6], relationships = [new Relationship{ relationshipType="mother", id = 5 }, new Relationship{ relationshipType="father", id = 4}] };
// Convert dictionary of family members to JSON string
jsonString string = jsonLib.convertToJSON(family);
// Show JSON string
SysLib.writeStdout(jsonString);

25
Task/JSON/EGL/json-3.egl Normal file
View file

@ -0,0 +1,25 @@
// Convert JSON string into dictionary of family members
family Dictionary;
jsonLib.convertFromJSON(jsonString, family);
// List family members and their relationships
familyMember FamilyMember;
relation FamilyMember;
keys string[] = family.getKeys();
for(i int from 1 to keys.getSize())
SysLib.writeStdout("----------------------------------------------------");
familyMember = family[keys[i]];
SysLib.writeStdout(familyMember.person.lastName + ", " + familyMember.person.firstName + " - " + familyMember.person.age);
for(j int from 1 to familyMember.relationships.getSize())
id string = familyMember.relationships[j].id;
relation = family[id];
SysLib.writeStdout(familyMember.relationships[j].relationshipType + ": " +
relation.person.lastName + ", " + relation.person.firstName);
end
end

15
Task/JSON/EGL/json-4.egl Normal file
View file

@ -0,0 +1,15 @@
// Service function definition
function geocode(address String) returns (GoogleGeocoding) {
@Resource{uri = "binding:GoogleGeocodingBinding"},
@Rest{method = _GET, uriTemplate = "/json?address={address}&sensor=false",
requestFormat = None, responseFormat = JSON}
}
// Invoke service function
call geocode("111 Maple Street, Somewhere, CO") returning to callback;
function callBack(result GoogleGeocoding in)
SysLib.writeStdout(result.status);
SysLib.writeStdout(result.results[1].geometry.location.lat);
SysLib.writeStdout(result.results[1].geometry.location.lng);
end

34
Task/JSON/EchoLisp/json.l Normal file
View file

@ -0,0 +1,34 @@
;; JSON standard types : strings, numbers, and arrays (vectors)
(export-json #(6 7 8 9)) → "[6,7,8,9]"
(export-json #("alpha" "beta" "gamma")) → "["alpha","beta","gamma"]"
(json-import "[6,7,8,9]") → #( 6 7 8 9)
(json-import #<< ["alpha","beta","gamma"] >>#) → #( "alpha" "beta" "gamma")
;; EchoLisp types : dates, rational, complex, big int
(export-json 3/4) → "{"_instanceof":"Rational","a":3,"b":4}"
(json-import #<< {"_instanceof":"Rational","a":666,"b":42} >>#) → 111/7
;; Symbols
(export-json 'Simon-Gallubert) → "{"_instanceof":"Symbol","name":"Simon-Gallubert"}"
(json-import #<< {"_instanceof":"Symbol","name":"Antoinette-de-Gabolde"} >>#)
→ Antoinette-de-Gabolde
;; Lists
(define my-list
(export-json '( 43 4 5 ( 6 7 ( 8 9 )))))
→ "{"_instanceof":"List" ,"array":[43,4,5,{"_instanceof":"List",
"array":[6,7,{"_instanceof":"List",
"array":[8,9],"circular":false}],"circular":false}],"circular":false}"
(json-import my-list) → (43 4 5 (6 7 (8 9)))
;; Structures
(struct Person (name pict)) → #struct:Person [name pict]
(define antoinette (Person "antoinette" "👰")) → # (antoinette 👰)
(export-json antoinette) →
"{"_instanceof":"Struct", "struct":"Person","id":17,"fields":["antoinette","👰"]}"
(json-import
#<< {"_instanceof":"Struct","struct":"Person","id":18,"fields":["simon","🎩"]} >>#)
→ # (simon 🎩)

View file

@ -0,0 +1,12 @@
import extensions;
import extensions'dynamic;
public program()
{
var json := "{ ""foo"": 1, ""bar"": [10, ""apples""] }";
var o := json.fromJson();
console.printLine("json.foo=",o.foo);
console.printLine("json.bar=",o.bar)
}

View file

@ -0,0 +1,18 @@
(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]}"

View file

@ -0,0 +1,19 @@
(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)))

41
Task/JSON/Erlang/json.erl Normal file
View file

@ -0,0 +1,41 @@
-module(json).
-export([main/0]).
main() ->
JSON =
"{
\"firstName\": \"John\",
\"lastName\": \"Smith\",
\"age\": 25,
\"address\": {
\"streetAddress\": \"21 2nd Street\",
\"city\": \"New York\",
\"state\": \"NY\",
\"postalCode\": \"10021\"
},
\"phoneNumber\": [
{
\"type\": \"home\",
\"number\": \"212 555-1234\"
},
{
\"type\": \"fax\",
\"number\": \"646 555-4567\"
}
]
}",
Erlang =
{struct,
[{"firstName","John"},
{"lastName","Smith"},
{"age",25},
{"address",
{struct,[{"streetAddress","21 2nd Street"},
{"city","New York"},
{"state","NY"},
{"postalCode","10021"}]}},
{"phoneNumber",
{array,[{struct,[{"type","home"},{"number","212 555-1234"}]},
{struct,[{"type","fax"},{"number","646 555-4567"}]}]}}]},
io:format("JSON -> Erlang\n~p\n",[mochijson:decode(JSON)]),
io:format("Erlang -> JSON\n~s\n",[mochijson:encode(Erlang)]).

View file

@ -0,0 +1,9 @@
open Newtonsoft.Json
type Person = {ID: int; Name:string}
let xs = [{ID = 1; Name = "First"} ; { ID = 2; Name = "Second"}]
let json = JsonConvert.SerializeObject(xs)
json |> printfn "%s"
let xs1 = JsonConvert.DeserializeObject<Person list>(json)
xs1 |> List.iter(fun x -> printfn "%i %s" x.ID x.Name)

View file

@ -0,0 +1,3 @@
[{"ID":1,"Name":"First"},{"ID":2,"Name":"Second"}]
1 First
2 Second

View file

@ -0,0 +1,14 @@
open FSharp.Data
open FSharp.Data.JsonExtensions
type Person = {ID: int; Name:string}
let xs = [{ID = 1; Name = "First"} ; { ID = 2; Name = "Second"}]
let infos = xs |> List.map(fun x -> JsonValue.Record([| "ID", JsonValue.Number(decimal x.ID); "Name", JsonValue.String(x.Name) |]))
|> Array.ofList |> JsonValue.Array
infos |> printfn "%A"
match JsonValue.Parse(infos.ToString()) with
| 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)

View file

@ -0,0 +1,12 @@
[
{
"ID": 1,
"Name": "First"
},
{
"ID": 2,
"Name": "Second"
}
]
1 "First"
2 "Second"

View file

@ -0,0 +1,7 @@
open FSharp.Data
type Person = {ID: int; Name:string}
type People = JsonProvider<""" [{"ID":1,"Name":"First"},{"ID":2,"Name":"Second"}] """>
People.GetSamples()
|> Array.map(fun x -> {ID = x.Id; Name = x.Name} )
|> Array.iter(fun x -> printfn "%i %s" x.ID x.Name)

View file

@ -0,0 +1,2 @@
1 First
2 Second

View file

@ -0,0 +1,10 @@
USING: json.writer json.reader ;
SYMBOL: foo
! Load a JSON string into a data structure
"[[\"foo\",1],[\"bar\",[10,\"apples\"]]]" json> foo set
! Create a new data structure and serialize into JSON
{ { "blue" { "ocean" "water" } } >json

View file

@ -0,0 +1,18 @@
using util
class Json
{
public static Void main ()
{
Str input := """{"blue": [1, 2], "ocean": "water"}"""
Map jsonObj := JsonInStream(input.in).readJson
echo ("Value for 'blue' is: " + jsonObj["blue"])
jsonObj["ocean"] = ["water":["cold", "blue"]]
Map ocean := jsonObj["ocean"]
echo ("Value for 'ocean/water' is: " + ocean["water"])
output := JsonOutStream(Env.cur.out)
output.writeJson(jsonObj)
echo ()
}
}

48
Task/JSON/Fortran/json.f Normal file
View file

@ -0,0 +1,48 @@
program json_fortran
use json_module
implicit none
type phonebook_type
character(len=:),allocatable :: name
character(len=:),allocatable :: phone
end type phonebook_type
type(phonebook_type), dimension(3) :: PhoneBook
integer :: i
type(json_value),pointer :: json_phonebook,p,e
type(json_file) :: json
PhoneBook(1) % name = 'Adam'
PhoneBook(2) % name = 'Eve'
PhoneBook(3) % name = 'Julia'
PhoneBook(1) % phone = '0000001'
PhoneBook(2) % phone = '0000002'
PhoneBook(3) % phone = '6666666'
call json_initialize()
!create the root structure:
call json_create_object(json_phonebook,'')
!create and populate the phonebook array:
call json_create_array(p,'PhoneBook')
do i=1,3
call json_create_object(e,'')
call json_add(e,'name',PhoneBook(i)%name)
call json_add(e,'phone',PhoneBook(i)%phone)
call json_add(p,e) !add this element to array
nullify(e) !cleanup for next loop
end do
call json_add(json_phonebook,p) !add p to json_phonebook
nullify(p) !no longer need this
!write it to a file:
call json_print(json_phonebook,'phonebook.json')
! read directly from a character string
call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
{ "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
! print it to the console
call json%print_file()
end program json_fortran

View file

@ -0,0 +1,15 @@
{
"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"
},
}
}

View file

@ -0,0 +1,17 @@
#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

View file

@ -0,0 +1 @@
println( eval('{ "foo": 1, "bar": [10, "apples"] }') )

View file

@ -0,0 +1,3 @@
import json.*
DefaultJSONWriter.write( JSONReader({'ints', 'bigInts'}).fromString('{ "foo": 1, "bar": [10, "apples"] }') )

View file

@ -0,0 +1,21 @@
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

25
Task/JSON/Go/json-1.go Normal file
View file

@ -0,0 +1,25 @@
package main
import "encoding/json"
import "fmt"
func main() {
var data interface{}
err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
if err == nil {
fmt.Println(data)
} else {
fmt.Println(err)
}
sample := map[string]interface{}{
"blue": []interface{}{1, 2},
"ocean": "water",
}
json_string, err := json.Marshal(sample)
if err == nil {
fmt.Println(string(json_string))
} else {
fmt.Println(err)
}
}

59
Task/JSON/Go/json-2.go Normal file
View file

@ -0,0 +1,59 @@
package main
import "encoding/json"
import "fmt"
type Person struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Addr *Address `json:"address,omitempty"`
Ph []string `json:"phone,omitempty"`
}
type Address struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
}
func main() {
// compare with output, note apt field ignored, missing fields
// have zero values.
jData := []byte(`{
"name": "Smith",
"address": {
"street": "21 2nd Street",
"apt": "507",
"city": "New York",
"state": "NY",
"zip": "10021"
}
}`)
var p Person
err := json.Unmarshal(jData, &p)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%+v\n %+v\n\n", p, p.Addr)
}
// compare with output, note empty fields omitted.
pList := []Person{
{
Name: "Jones",
Age: 21,
},
{
Name: "Smith",
Addr: &Address{"21 2nd Street", "New York", "NY", "10021"},
Ph: []string{"212 555-1234", "646 555-4567"},
},
}
jData, err = json.MarshalIndent(pList, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(jData))
}
}

View file

@ -0,0 +1 @@
gw.lang.reflect.json.Json#fromJson( String json ) : javax.script.Bindings

View file

@ -0,0 +1,20 @@
{
"Name": "Dickson Yamada",
"Age": 39,
"Address": {
"Number": 9604,
"Street": "Donald Court",
"City": "Golden Shores",
"State": "FL"
},
"Hobby": [
{
"Category": "Sport",
"Name": "Baseball"
},
{
"Category": "Recreation",
"Name": "Hiking"
}
]
}

View file

@ -0,0 +1,3 @@
var personUrl = new URL( "http://gosu-lang.github.io/data/person.json" )
var person: Dynamic = personUrl.JsonContent
print( person.Name )

View file

@ -0,0 +1 @@
personUrl.JsonContent

View file

@ -0,0 +1 @@
print( person.toStructure( "Person", false ) )

View file

@ -0,0 +1,28 @@
structure Person {
static function fromJson( jsonText: String ): Person {
return gw.lang.reflect.json.Json.fromJson( jsonText ) as Person
}
static function fromJsonUrl( url: String ): Person {
return new java.net.URL( url ).JsonContent
}
static function fromJsonUrl( url: java.net.URL ): Person {
return url.JsonContent
}
static function fromJsonFile( file: java.io.File ) : Person {
return fromJsonUrl( file.toURI().toURL() )
}
property get Address(): Address
property get Hobby(): List<Hobby>
property get Age(): Integer
property get Name(): String
structure Address {
property get Number(): Integer
property get State(): String
property get Street(): String
property get City(): String
}
structure Hobby {
property get Category(): String
property get Name(): String
}
}

View file

@ -0,0 +1,4 @@
var person = Person.fromJsonUrl( personUrl )
print( person.Name )
print( person.Address.City )
print( person.Hobby[0].Name )

View file

@ -0,0 +1,3 @@
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

View file

@ -0,0 +1 @@
var clone = eval( person.toGosu() )

View file

@ -0,0 +1,13 @@
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText('''
{
"people":[
{"name":{"family":"Flintstone","given":"Frederick"},"age":35,"relationships":{"wife":"people[1]","child":"people[4]"}},
{"name":{"family":"Flintstone","given":"Wilma"},"age":32,"relationships":{"husband":"people[0]","child":"people[4]"}},
{"name":{"family":"Rubble","given":"Barnard"},"age":30,"relationships":{"wife":"people[3]","child":"people[5]"}},
{"name":{"family":"Rubble","given":"Elisabeth"},"age":32,"relationships":{"husband":"people[2]","child":"people[5]"}},
{"name":{"family":"Flintstone","given":"Pebbles"},"age":1,"relationships":{"mother":"people[1]","father":"people[0]"}},
{"name":{"family":"Rubble","given":"Bam-Bam"},"age":1,"relationships":{"mother":"people[3]","father":"people[2]"}},
]
}
''')

View file

@ -0,0 +1,8 @@
result.each { println it.key; it.value.each {person -> println person} }
assert result.people[0].name == [family:'Flintstone', given:'Frederick']
assert result.people[4].age == 1
assert result.people[2].relationships.wife == 'people[3]'
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']

View file

@ -0,0 +1,4 @@
$data = json_decode(''{ "foo": 1, "bar": [10, "apples"] }'');
$sample = ["blue" => [1, 2], "ocean" => "water"];
$jsonstring = json_encode($sample, ["pretty_print" => true]);

View file

@ -0,0 +1,2 @@
LOCAL arr
hb_jsonDecode( '[101,[26,"Test1"],18,false]', @arr )

View file

@ -0,0 +1,4 @@
LOCAL arr := { 101, { 18, "Test1" }, 18, .F. }
? hb_jsonEncode( arr )
// The output is:
// [101,[26,"Test1"],18,false]

View file

@ -0,0 +1,24 @@
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import Data.Attoparsec (parseOnly)
import Data.Text
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Char8 as S
testdoc = object [
"foo" .= (1 :: Int),
"bar" .= ([1.3, 1.6, 1.9] :: [Double]),
"baz" .= ("some string" :: Text),
"other" .= object [
"yes" .= ("sir" :: Text)
]
]
main = do
let out = encode testdoc
B.putStrLn out
case parseOnly json (S.concat $ B.toChunks out) of
Left e -> error $ "strange error re-parsing json: " ++ (show e)
Right v | v /= testdoc -> error "documents not equal!"
Right v | otherwise -> print v

View file

@ -0,0 +1,16 @@
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
import Data.Aeson
import Data.Aeson.TH
data Person = Person { firstName :: String
, lastName :: String
, age :: Maybe Int
} deriving (Show, Eq)
$(deriveJSON defaultOptions ''Person)
main = do
let test1 = "{\"firstName\":\"Bob\", \"lastName\":\"Smith\"}"
test2 = "{\"firstName\":\"Miles\", \"lastName\":\"Davis\", \"age\": 45}"
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)

View file

@ -0,0 +1,17 @@
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
import Data.Aeson
import GHC.Generics
data Person = Person { firstName :: String
, lastName :: String
, age :: Maybe Int
} deriving (Show, Eq, Generic)
instance FromJSON Person
instance ToJSON Person
main = do
let test1 = "{\"firstName\":\"Bob\", \"lastName\":\"Smith\"}"
test2 = "{\"firstName\":\"Miles\", \"lastName\":\"Davis\", \"age\": 45}"
print (decode test1 :: Maybe Person)
print (decode test2 :: Maybe Person)

15
Task/JSON/Hoon/json.hoon Normal file
View file

@ -0,0 +1,15 @@
:- %say
|= [^ [in=@tas ~] ~]
:- %noun
=+ obj=(need (poja in)) :: try parse to json
=+ typ=$:(name=@tas age=@ud) :: datastructure
=+ spec=(ot name/so age/ni ~):jo :: parsing spec
?. ?=([%o *] obj) :: isnt an object?
~
=+ ^= o
%. %. (spec obj) :: parse with spec
need :: panic if failed
,typ :: cast to type
=. 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

50
Task/JSON/J/json-1.j Normal file
View file

@ -0,0 +1,50 @@
NB. character classes:
NB. 0: whitespace
NB. 1: "
NB. 2: \
NB. 3: [ ] , { } :
NB. 4: ordinary
classes=.3<. '"\[],{}:' (#@[ |&>: i.) a.
classes=.0 (I.a.e.' ',CRLF,TAB)} (]+4*0=])classes
words=:(0;(0 10#:10*".;._2]0 :0);classes)&;: NB. states:
0.0 1.1 2.1 3.1 4.1 NB. 0 whitespace
1.0 5.0 6.0 1.0 1.0 NB. 1 "
4.0 4.0 4.0 4.0 4.0 NB. 2 \
0.3 1.2 2.2 3.2 4.2 NB. 3 { : , } [ ]
0.3 1.2 2.0 3.2 4.0 NB. 4 ordinary
0.3 1.2 2.2 3.2 4.2 NB. 5 ""
1.0 1.0 1.0 1.0 1.0 NB. 6 "\
)
tokens=. ;:'[ ] , { } :'
actions=: lBra`rBracket`comma`lBra`rBrace`colon`value
NB. action verbs argument conventions:
NB. x -- boxed json word
NB. y -- boxed json state stack
NB. result -- new boxed json state stack
NB.
NB. json state stack is an list of boxes of incomplete lists
NB. (a single box for complete, syntactically valid json)
jsonParse=: 0 {:: (,a:) ,&.> [: actions@.(tokens&i.@[)/ [:|.a:,words
lBra=: a: ,~ ]
rBracket=: _2&}.@], [:< _2&{::@], _1&{@]
comma=: ]
rBrace=: _2&}.@], [:< _2&{::@](, <) [:|: (2,~ [: -:@$ _1&{::@]) $ _1&{::@]
colon=: ]
value=: _1&}.@], [:< _1&{::@], jsonValue&.>@[
NB. hypothetically, jsonValue should strip double quotes
NB. interpret back slashes
NB. and recognize numbers
jsonValue=:]
require'strings'
jsonSer2=: jsonSer1@(<"_1^:(0>.#@$-1:))
jsonSer1=: ']' ,~ '[' }:@;@; (',' ,~ jsonSerialize)&.>
jsonSer0=: '"', jsonEsc@:":, '"'"_
jsonEsc=: rplc&(<;._1' \ \\ " \"')
jsonSerialize=:jsonSer0`jsonSer2@.(*@L.)

13
Task/JSON/J/json-2.j Normal file
View file

@ -0,0 +1,13 @@
jsonParse'{ "blue": [1,2], "ocean": "water" }'
┌────────────────┐
│┌──────┬───────┐│
││"blue"│"ocean"││
│├──────┼───────┤│
││┌─┬─┐ │"water"││
│││1│2│ │ ││
││└─┴─┘ │ ││
│└──────┴───────┘│
└────────────────┘
└──────────────────────────────┘
jsonSerialize jsonParse'{ "blue": [1,2], "ocean": "water" }'
[[["\"blue\"","\"ocean\""],[["1","2"],"\"water\""]]]

43
Task/JSON/Java/json.java Normal file
View file

@ -0,0 +1,43 @@
import com.google.gson.Gson;
public class JsonExample {
public static void main(String[] args) {
Gson gson = new Gson();
String json = "{ \"foo\": 1, \"bar\": [ \"10\", \"apples\"] }";
MyJsonObject obj = gson.fromJson(json, MyJsonObject.class);
System.out.println(obj.getFoo());
for(String bar : obj.getBar()) {
System.out.println(bar);
}
obj = new MyJsonObject(2, new String[] { "20", "oranges" });
json = gson.toJson(obj);
System.out.println(json);
}
}
class MyJsonObject {
private int foo;
private String[] bar;
public MyJsonObject(int foo, String[] bar) {
this.foo = foo;
this.bar = bar;
}
public int getFoo() {
return foo;
}
public String[] getBar() {
return bar;
}
}

View file

@ -0,0 +1,4 @@
var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
var sample = { "blue": [1,2], "ocean": "water" };
var json_string = JSON.stringify(sample);

1
Task/JSON/Jq/json-1.jq Normal file
View file

@ -0,0 +1 @@
.

1
Task/JSON/Jq/json-2.jq Normal file
View file

@ -0,0 +1 @@
jq -c . data.json

1
Task/JSON/Jq/json-3.jq Normal file
View file

@ -0,0 +1 @@
jq tostring data.json

View file

@ -0,0 +1,14 @@
prompt$ jsish
Jsish interactive: see 'help [cmd]'
# var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }');
variable
# data
{ bar:[ 10, "apples" ], foo:1 }
# var sample = { blue: [1,2], ocean: "water" };
variable
# sample
{ blue:[ 1, 2 ], ocean:"water" }
# puts(JSON.stringify(sample))
{ "blue":[ 1, 2 ], "ocean":"water" }

View file

@ -0,0 +1,13 @@
# Pkg.add("JSON") ... an external library http://docs.julialang.org/en/latest/packages/packagelist/
using JSON
sample = Dict()
sample["blue"] = [1, 2]
sample["ocean"] = "water"
@show sample jsonstring = json(sample)
@show jsonobj = JSON.parse(jsonstring)
@assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}"
@assert jsonobj == Dict("ocean" => "water", "blue" => [1, 2])
@assert typeof(jsonobj) == Dict{String, Any}

View file

@ -0,0 +1,15 @@
// version 1.2.21
data class JsonObject(val foo: Int, val bar: Array<String>)
data class JsonObject2(val ocean: String, val blue: Array<Int>)
fun main(args: Array<String>) {
// JSON to object
val data: JsonObject = JSON.parse("""{ "foo": 1, "bar": ["10", "apples"] }""")
println(JSON.stringify(data))
// object to JSON
val data2 = JsonObject2("water", arrayOf(1, 2))
println(JSON.stringify(data2))
}

1
Task/JSON/LFE/json-1.lfe Normal file
View file

@ -0,0 +1 @@
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14))

2
Task/JSON/LFE/json-2.lfe Normal file
View file

@ -0,0 +1,2 @@
(: erlang binary_to_list
(: jiffy encode (list 1 2 3 '"apple" 'true 3.14)))

1
Task/JSON/LFE/json-3.lfe Normal file
View file

@ -0,0 +1 @@
(: jiffy decode '"[1,2,3,[97,112,112,108,101],true,3.14]")

1
Task/JSON/LFE/json-4.lfe Normal file
View file

@ -0,0 +1 @@
(: jiffy decode '"{\"foo\": [1, 2, 3]}")

3
Task/JSON/LFE/json-5.lfe Normal file
View file

@ -0,0 +1,3 @@
(let (((tuple (list (tuple key value)))
(: jiffy decode '"{\"foo\": [1, 2, 3]}")))
(: io format '"~p: ~p~n" (list key value)))

View file

@ -0,0 +1,35 @@
// Javascript objects are represented by maps in Lasso
local(mymap = map(
'success' = true,
'numeric' = 11,
'string' = 'Eleven'
))
json_serialize(#mymap) // {"numeric": 11,"string": "Eleven","success": true}
'<br />'
// Javascript arrays are represented by arrays
local(opendays = array(
'Monday',
'Tuesday'
))
local(closeddays = array(
'Wednesday',
'Thursday',
'Friday'
))
json_serialize(#opendays) // ["Monday", "Tuesday"]
'<br />'
json_serialize(#closeddays) // ["Wednesday", "Thursday", "Friday"]
'<br />'
#mymap -> insert('Open' = #opendays)
#mymap -> insert('Closed' = #closeddays)
local(myjson = json_serialize(#mymap))
#myjson // {"Closed": ["Wednesday", "Thursday", "Friday"],"numeric": 11,"Open": ["Monday", "Tuesday"],"string": "Eleven","success": true}
'<br />'
json_deserialize(#myjson) // map(Closed = array(Wednesday, Thursday, Friday), numeric = 11, Open = array(Monday, Tuesday), string = Eleven, success = true)

View file

@ -0,0 +1,45 @@
//--------------------------------------
// Simple (unsafe) JSON decoder based on eval()
// @param {string} json
// @return {any}
//--------------------------------------
function json_decode (json){
var o;
eval('o='+json);
return _json_decode_val(o);
}
function _json_decode_val (o){
if (o==null) return undefined;
switch(typeof(o)){
case "object":
if (o instanceof Array){
var v = list();
var cnt = o.length;
for (i=0;i<cnt;i++){
v.add(_json_decode_val(o[i]));
}
}else{
var v = propList();
for (var i in o){
var p = i;
v.setAProp(_json_decode_val(p), _json_decode_val(o[i]));
}
}
return v;
case "string":
// optional support of special Lingo data type 'symbol' unknown to JavaScript
if (o.substr(0,7)=='__sym__') return symbol(o.substr(7));
return o;
default:
return o;
}
}
function _json_escape_string (str){
var hash={"\\":"\\\\", "/":"\\/", "\n":"\\n", "\t":"\\t", "\r":"\\r", "\b":"\\b", "\f":"\\f", "\"":"\\\""};
var patt = "["; for (i in hash) patt+=i;patt+="]";
return str.replace(RegExp(patt, "g"), function(c){
return hash[c]
});
}

View file

@ -0,0 +1,50 @@
----------------------------------------
-- JSON encoder
-- Supported Lingo data types: VOID, integer, float, string, symbol, list, propList
-- @param {any} o
-- @return {string}
----------------------------------------
on json_encode (o)
case ilk(o) of
#void:
return "null"
#integer, #float:
return string(o)
#string:
return QUOTE & _json_escape_string(o) & QUOTE
#list:
res = []
repeat with v in o
res.add(json_encode(v))
end repeat
return "[" & _cimplode(res) & "]"
#propList:
res = []
cnt = count(o)
repeat with i = 1 to cnt
p = o.getPropAt(i)
v = o[i]
res.add( json_encode(p)&":"&json_encode(v) )
end repeat
return "{" & _cimplode(res) & "}"
#symbol:
-- optional support of special Lingo data type 'symbol' unknown to JavaScript
return QUOTE &"__sym__"&_json_escape_string(string(o)) & QUOTE
otherwise:
put "ERROR: unsupported data type"
end case
end
----------------------------------------
-- Implodes list into comma-separated string
-- @param {list} l
-- @return {string}
----------------------------------------
on _cimplode (l)
str=""
repeat with i=1 to l.count
put l[i]&"," after str
end repeat
delete the last char of str
return str
end

View file

@ -0,0 +1,16 @@
data_org = [\
42,\
3.14159,\
[2, 4, #fooBar, "apples", "bananas", "cherries" ],\
["foo": 1, #bar: VOID, "Hello": "world!"],\
VOID\
]
json_str = json_encode(data_org) -- valid according to JSONLint
data_decoded = json_decode(json_str)
put data_org
-- [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>]

38
Task/JSON/Lua/json.lua Normal file
View file

@ -0,0 +1,38 @@
local json = require("json")
local json_data = [=[[
42,
3.14159,
[ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ],
{ "H": 1, "He": 2, "X": null, "Li": 3 },
null,
true,
false
]]=]
print("Original JSON: " .. json_data)
local data = json.decode(json_data)
json.util.printValue(data, 'Lua')
print("JSON re-encoded: " .. json.encode(data))
local data = {
42,
3.14159,
{
2, 4, 8, 16, 32, 64,
"apples",
"bananas",
"cherries"
},
{
H = 1,
He = 2,
X = json.util.null(),
Li = 3
},
json.util.null(),
true,
false
}
print("JSON from new Lua data: " .. json.encode(data))

View file

@ -0,0 +1,111 @@
MODULE A {
\\ Process data in json format
\\ We can load from external file with Inline "libName"
\\ or multiple files Inline "file1" && "file2"
\\ but here we have the library in a module
Inline Code Lib1
\\ So now we make a Parser object (a group type in M2000)
Parser=ParserClass()
\\ We can display any function, module that is public and known list
Modules ?
\\ And this are all known variables (or and objects)
List !
Document json$
\\ We can load from file
\\ Load.Doc json$, "alfa.json"
json$={{
"alfa":-0.11221e+12,
"array" : [
-0.67,
"alfa1",
[
10,
20
],
"beta1",
1.21e12,
21.12145,
"ok"
],
"delta": false, "epsilon" : true, "Null Value" : null
}}
Save.Doc json$, "json2.json" \\ by default in Utf-8 with BOM
\\ just show multiline text
\\ Report display lines and stop after 3/4 of console height lines
\\ just press a key or click mouse button
Report json$
\\ so now we get text to a new object
alfa=Parser.Eval(json$)
\\ check it
Print Type$(alfa) ' it is a group
Print "alfa.type$=";alfa.type$ \\ this is a read only property
Report "as one line"
Report Parser.Ser$(alfa, 0)
Report "as multiline"
Report Parser.Ser$(alfa, 1)
Print "Using Print"
Print Parser.ReadAnyString$(alfa)
Print "Value for alfa, id alfa"
Print Parser.ReadAnyString$(alfa,"alfa")
Report "as multiline"
Report Parser.Ser$(Parser.Eval(Parser.ReadAnyString$(alfa,"array", 2)), 1)
\\ We get a copy of an array as a Group (a group which return an array)
Alfa3=Parser.Eval(Parser.ReadAnyString$(alfa,"array", 2))
\\ First value is for actual object, second value is a readonly property of this object
Print type$(Alfa3), Alfa3.type$
Dim B()
\\ Now Alfa3 run Value part and pass a pointer of array
\\ B() is an array and here take a pointer to Alfa3 array (as value of Alfa3)
B()=Alfa3
\\ each() make an iterator for B()
N=each(B())
While N {
\\ Using B() we get values always. but if we have "object" or "array" then Print prints items **
Print B(N^)
}
\\ Print show here nothing because if value is object then "print" just leave a column and continue to next one
Print B()
\\ we have to use Group() to get group not value of group (if any).
\\ Group() works for "named" group, not for stored in an array or an inventory or a stack
Print Parser.StringValue$(Group(Alfa3), 0)
Print Parser.StringValue$(Group(Alfa3), 1)
\\ Now we want to pass a new value
\\ Interpreter want to match type of expression from left side to right side
\\ Because Parser.StringValue$ is actual a Group (As property),
\\ we have a second linked name: Parser.StringValue
\\ we have to use Parser.StringValue()
\\ and all values must be groups, as those provided by Parser
Parser.StringValue(Group(Alfa3), 1)=Parser.Numeric(1234)
Print Parser.StringValue$(Group(Alfa3), 1)
Print Parser.StringValue$(Group(Alfa), "array", 2, 0)
\\ we have to use Parser.StringValue$()
Parser.StringValue$(Group(Alfa), "array", 2, 0)=Parser.JString$("Changed to String")
Print Parser.StringValue$(Group(Alfa), "array", 2,0)
Try ok {
Print Parser.StringValue$(Group(Alfa), "array", 2)
}
If Error or not ok Then Print Error$
Parser.StringValue.Add = True
Parser.StringValue$(Group(Alfa), "array", 2, 10)=Parser.JString$("Changed to String 2")
Parser.StringValue(Group(Alfa), "Last value")=Parser.Boolean(true)
Report "as multiline"
Report Parser.Ser$(alfa3, 1)
Report Parser.Ser$(alfa, 1)
Parser.StringValue.Add = False
Parser.StringValue.Del = True
Parser.StringValue(Group(Alfa), "array", 0)=Parser.Null()
Parser.StringValue(Group(Alfa), "delta")=Parser.Null()
Parser.StringValue.Del = False
For Parser {
.StringValue(Group(Alfa), "array", 1,5)=.Arr((.Numeric(10), .Jstring$("ok 20"), .Boolean(true)))
}
Report Parser.Ser$(alfa, 1)
}
// call A
A

9
Task/JSON/MATLAB/json.m Normal file
View file

@ -0,0 +1,9 @@
>> jsondecode('{ "foo": 1, "bar": [10, "apples"] }')
ans =
struct with fields:
foo: 1
bar: {2×1 cell}
>> jsonencode(ans)
ans =
{"foo":1,"bar":[10,"apples"]}

View file

@ -0,0 +1,4 @@
> JSON:-ParseString("[{\"tree\": \"maple\", \"count\": 21}]");
[table(["tree" = "maple", "count" = 21])]
> JSON:-ToString( [table(["tree" = "maple", "count" = 21])] );
"[{\"count\": 21, \"tree\": \"maple\"}]"

View file

@ -0,0 +1,2 @@
data = ImportString["{ \"foo\": 1, \"bar\": [10, \"apples\"] }","JSON"]
ExportString[data, "JSON"]

View file

@ -0,0 +1,137 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.List
import org.json.JSONObject
import org.json.JSONArray
import org.json.JSONTokener
import org.json.JSONException
/**
* Using library from json.org
*
* @see http://www.json.org/java/index.html
*/
class RJson01 public
properties private constant
JSON_DWARFS = '' -
'{\n' -
' "F1937_1" : {\n' -
' "title" : "Snow White and the Seven Dwarfs",\n' -
' "year" : 1937,\n' -
' "medium" : "film",\n' -
' "dwarfs" : [ "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey", "Doc" ]\n' -
' },\n' -
' "F2012_1" : {\n' -
' "title" : "Mirror, Mirror",\n' -
' "year" : 2012,\n' -
' "medium" : "film",\n' -
' "dwarfs" : [ "Grimm", "Butcher", "Wolf", "Napoleon", "Half Pint", "Grub", "Chuckles" ]\n' -
' },\n' -
'}'
/**
* A bean that looks like the following JSON
* <pre>
* {
* "F2012_2" : {
* "title" : "Snow White & the Huntsman",
* "year" : 2012,
* "medium" : "film",
* "dwarfs" : [ "Beith", "Quert", "Muir", "Coll", "Duir", "Gus", "Gort", "Nion" ]
* }
* }
* </pre>
*/
SAMPLE_BEAN = DwarfBean( -
"F2012_2", -
"Snow White & the Huntsman", -
Long(2012), -
"film", -
Arrays.asList([String "Beith", "Quert", "Muir", "Coll", "Duir", "Gus", "Gort", "Nion"]) -
)
method main(args = String[]) public static
say json2bean(JSON_DWARFS)
say
say bean2json(SAMPLE_BEAN)
say
return
method json2bean(dwarfs) public static returns List
say "Make beans from this JSON string:"
say dwarfs
jsonBeans = ArrayList()
do
jd = JSONObject(JSONTokener(dwarfs))
ns = JSONObject.getNames(jd)
name = String
loop name over ns
dwarves = ArrayList()
jn = jd.getJSONObject(name)
title = jn.getString('title')
year = Long(jn.getLong('year'))
medium = jn.getString('medium')
dwa = jn.getJSONArray('dwarfs')
loop di = 0 to dwa.length() - 1
dwarves.add(dwa.getString(di))
end di
jb = DwarfBean(name, title, year, medium, dwarves)
jsonBeans.add(jb.toString())
end name
catch ex = JSONException
ex.printStackTrace()
end
return jsonBeans
method bean2json(sb = DwarfBean) public static returns String
say "Make JSONObject from this bean:"
say sb
jsonString = String
do
jd = JSONObject(sb)
jo = JSONObject()
jo = jo.put(sb.keyGet(), jd)
jsonString = jo.toString(2)
catch ex = JSONException
ex.printStackTrace()
end
return jsonString
-- =============================================================================
class RJson01.DwarfBean public binary
properties private
key = String -- not part of bean
properties indirect
title = String
year = Long
medium = String
dwarfs = List
method DwarfBean(key_ = String null, title_ = String null, year_ = Long null, medium_ = String null, dwarfs_ = List null) public
keyPut(key_)
setTitle(title_)
setYear(year_)
setMedium(medium_)
setDwarfs(dwarfs_)
return
method keyPut(key_ = String) public
key = key_
return
method keyGet() returns String
return key
method toString public returns String
ts = StringBuilder()
ts.append(String.format("%s@%08x ", [Object this.getClass().getSimpleName(), Integer(hashCode())]))
ts.append('[')
ts.append('key='String.valueOf(keyGet())', ')
ts.append('title='String.valueOf(getTitle())', ')
ts.append('year='String.valueOf(getYear())', ')
ts.append('medium='String.valueOf(getMedium())', ')
ts.append('dwarfs='String.valueOf(getDwarfs()))
ts.append(']')
return ts.toString()

View file

@ -0,0 +1,81 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
import com.google.gson.
import java.util.List
/**
* Using google-gson library
*
* @see https://code.google.com/p/google-gson/
*/
class RJson02 public
properties private constant
JSON_DWARFS = '' -
'{\n' -
' "title" : "Snow White and the Seven Dwarfs",\n' -
' "year" : 1937,\n' -
' "medium": "film",\n' -
' "dwarfs": [ "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey", "Doc" ]\n' -
'}'
/**
* A bean that looks like the following JSON
* <pre>
* {
* "title" : "Snow White & the Huntsman",
* "year" : 2012,
* "medium" : "film",
* "dwarfs" : [ "Beith", "Quert", "Muir", "Coll", "Duir", "Gus", "Gort", "Nion" ]
* }
* </pre>
*/
SAMPLE_BEAN = RJSON02.DwarfBean( -
/*"F2012_2",*/ -
"Snow White and the Huntsman", -
Long(2012), -
"film", -
Arrays.asList([String "Beith", "Quert", "Muir", "Coll", "Duir", "Gus", "Gort", "Nion"]) -
)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
gsonObj = GsonBuilder().setPrettyPrinting().create()
jsonBean = RJson02.DwarfBean gsonObj.fromJson(JSON_DWARFS, RJson02.DwarfBean.class)
say JSON_DWARFS
say jsonBean.toString()
say
json = gsonObj.toJson(SAMPLE_BEAN);
say json
say SAMPLE_BEAN.toString()
say
return
-- =============================================================================
class RJson02.DwarfBean public binary
properties indirect
title = String
year = Long
medium = String
dwarfs = List
method DwarfBean(title_ = String null, year_ = Long null, medium_ = String null, dwarfs_ = List null) public
setTitle(title_)
setYear(year_)
setMedium(medium_)
setDwarfs(dwarfs_)
return
method toString public returns String
ts = StringBuilder()
ts.append(String.format("%s@%08x ", [Object this.getClass().getSimpleName(), Integer(hashCode())]))
ts.append('[')
ts.append('title='String.valueOf(getTitle())', ')
ts.append('year='String.valueOf(getYear())', ')
ts.append('medium='String.valueOf(getMedium())', ')
ts.append('dwarfs='String.valueOf(getDwarfs()))
ts.append(']')
return ts.toString()

8
Task/JSON/Nim/json.nim Normal file
View file

@ -0,0 +1,8 @@
import json
var data = parseJson("""{ "foo": 1, "bar": [10, "apples"] }""")
echo data["foo"]
echo data["bar"]
var js = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}]
echo js

View file

@ -0,0 +1,24 @@
type json item =
< name "Name": string;
kingdom "Kingdom": string;
phylum "Phylum": string;
class_ "Class": string;
order "Order": string;
family "Family": string;
tribe "Tribe": string
>
let str = "
{
\"Name\": \"camel\",
\"Kingdom\": \"Animalia\",
\"Phylum\": \"Chordata\",
\"Class\": \"Mammalia\",
\"Order\": \"Artiodactyla\",
\"Family\": \"Camelidae\",
\"Tribe\": \"Camelini\"
}"
let () =
let j = Json_io.json_of_string str in
print_endline (Json_io.string_of_json j);

Some files were not shown because too many files have changed in this diff Show more