First commit of partial RosettaCode contents.

Pushing this for testing purposes. Lots of work still needed.
This commit is contained in:
Ingy döt Net 2013-04-08 13:02:41 -07:00
commit 1e05ecd7ee
781 changed files with 9080 additions and 0 deletions

2
Task/JSON/0DESCRIPTION Normal file
View file

@ -0,0 +1,2 @@
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 (http://www.jsonlint.com/).

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

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))
}
}

25
Task/JSON/Go/json.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)
}
}

24
Task/JSON/Haskell/json.hs Normal file
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

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 @@
var data = eval('(' + '{ "foo": 1, "bar": [10, "apples"] }' + ')');

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);

7
Task/JSON/PHP/json.php Normal file
View file

@ -0,0 +1,7 @@
<?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
$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>

6
Task/JSON/Perl/json.pl Normal file
View file

@ -0,0 +1,6 @@
use JSON;
my $data = decode_json('{ "foo": 1, "bar": [10, "apples"] }');
my $sample = { blue => [1,2], ocean => "water" };
my $json_string = encode_json($sample);

49
Task/JSON/PicoLisp/json.l Normal file
View file

@ -0,0 +1,49 @@
(de checkJson (X Item)
(unless (= X Item)
(quit "Bad JSON" Item) ) )
(de readJson ()
(case (read "_")
("{"
(make
(for (X (readJson) (not (= "}" X)) (readJson))
(checkJson ":" (readJson))
(link (cons X (readJson)))
(T (= "}" (setq X (readJson))))
(checkJson "," X) ) ) )
("["
(make
(link T) # Array marker
(for (X (readJson) (not (= "]" X)) (readJson))
(link X)
(T (= "]" (setq X (readJson))))
(checkJson "," X) ) ) )
(T
(let X @
(cond
((pair X) (pack X))
((and (= "-" X) (format (peek)))
(- (read)) )
(T X) ) ) ) ) )
(de printJson (Item) # For simplicity, without indentation
(cond
((atom Item) (if Item (print @) (prin "{}")))
((=T (car Item))
(prin "[")
(map
'((X)
(printJson (car X))
(and (cdr X) (prin ", ")) )
(cdr Item) )
(prin "]") )
(T
(prin "{")
(map
'((X)
(print (caar X))
(prin ": ")
(printJson (cdar X))
(and (cdr X) (prin ", ")) )
Item )
(prin "}") ) ) )

View file

@ -0,0 +1,4 @@
>>> true = True; false = False; null = None
>>> data = eval('{ "foo": 1, "bar": [10, "apples"] }')
>>> data
{'foo': 1, 'bar': [10, 'apples']}

10
Task/JSON/Python/json.py Normal file
View file

@ -0,0 +1,10 @@
>>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}

7
Task/JSON/Ruby/json.rb Normal file
View file

@ -0,0 +1,7 @@
require 'json'
ruby_obj = JSON.parse('{"blue": [1, 2], "ocean": "water"}')
p ruby_obj
puts ruby_obj.class
puts ruby_obj["blue"].class
ruby_obj["ocean"] = {"water" => %w{fishy salty}}
puts JSON.generate(ruby_obj)

View file

@ -0,0 +1,8 @@
scala> import scala.util.parsing.json.{JSON, JSONObject}
import scala.util.parsing.json.{JSON, JSONObject}
scala> JSON.parseFull("""{"foo": "bar"}""")
res0: Option[Any] = Some(Map(foo -> bar))
scala> JSONObject(Map("foo" -> "bar")).toString()
res1: String = {"foo" : "bar"}

56
Task/JSON/Tcl/json-2.tcl Normal file
View file

@ -0,0 +1,56 @@
package require Tcl 8.6
proc tcl2json value {
# Guess the type of the value; deep *UNSUPPORTED* magic!
regexp {^value is a (.*?) with a refcount} \
[::tcl::unsupported::representation $value] -> type
switch $type {
string {
# Skip to the mapping code at the bottom
}
dict {
set result "{"
set pfx ""
dict for {k v} $value {
append result $pfx [tcl2json $k] ": " [tcl2json $v]
set pfx ", "
}
return [append result "}"]
}
list {
set result "\["
set pfx ""
foreach v $value {
append result $pfx [tcl2json $v]
set pfx ", "
}
return [append result "\]"]
}
int - double {
return [expr {$value}]
}
booleanString {
return [expr {$value ? "true" : "false"}]
}
default {
# Some other type; do some guessing...
if {$value eq "null"} {
# Tcl has *no* null value at all; empty strings are semantically
# different and absent variables aren't values. So cheat!
return $value
} elseif {[string is integer -strict $value]} {
return [expr {$value}]
} elseif {[string is double -strict $value]} {
return [expr {$value}]
} elseif {[string is boolean -strict $value]} {
return [expr {$value ? "true" : "false"}]
}
}
}
# For simplicity, all "bad" characters are mapped to \u... substitutions
set mapped [subst -novariables [regsub -all {[][\u0000-\u001f\\""]} \
$value {[format "\\\\u%04x" [scan {& } %c]]}]]
return "\"$mapped\""
}

2
Task/JSON/Tcl/json-3.tcl Normal file
View file

@ -0,0 +1,2 @@
set d [dict create blue [list 1 2] ocean water]
puts [tcl2json $d]

5
Task/JSON/Tcl/json.tcl Normal file
View file

@ -0,0 +1,5 @@
package require json
set sample {{ "foo": 1, "bar": [10, "apples"] }}
set parsed [json::json2dict $sample]
puts $parsed