JSON: Difference between revisions

1,753 bytes added ,  3 years ago
add Emacs Lisp JSON encoding/decoding
(add Emacs Lisp JSON encoding/decoding)
Line 1,191:
json.bar=10,apples
</pre>
 
=={{header|Emacs Lisp}}==
A JSON encoder and decoder is in package json, so load it first:
<lang Lisp>(require 'json)</lang>
===Decoding===
<lang Lisp>(setq example "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}")
(json-read-from-string example)
</lang>
{{out}}
<lang Lisp>((foo . "bar")
(baz .
[1 2 3]))</lang>
===Decoding, representing data as property lists===
<lang Lisp>(let ((json-object-type 'plist))
(json-read-from-string))</lang>
{{out}}
<lang Lisp>(:foo "bar" :baz
[1 2 3])</lang>
===Decoding, representing data as hash table===
<lang Lisp>(let ((json-object-type 'hash-table))
(json-read-from-string example))</lang>
{{out}}
<pre>#<hash-table equal 2/65 0x1563c39805fb></pre>
 
===Encoding===
<Lang Lisp>(json-encode example-object)</Lang>
{{out}}
<pre>"{\"list\":{\"cons\":[[\"quote\",\"x\"],2],\"cons\":[[\"quote\",\"y\"],\"a string\"]}}"</pre>
===Encoding, pretty printing output===
<lang Lisp>(let ((json-encoding-pretty-print t))
(json-encode example-object))</lang>
{{out}}
<pre>
"{
\"list\": {
\"cons\": [
[
\"quote\",
\"x\"
],
2
],
\"cons\": [
[
\"quote\",
\"y\"
],
\"a string\"
]
}
}"
</pre>
===Encoding, with options===
<lang Lisp>(let* ((json-encoding-pretty-print t)
(json-object-type 'alist)
(json-array-type 'vector)
(json-key-type 'symbol)
(vec (make-vector 3 "element")))
(aset vec 1 "second")
(aset vec 2 -3)
(json-encode (list (cons 'x 2)
(cons 'y "a string")
(cons 'z vec))))</lang>
{{out}}
<pre>"{
\"x\": 2,
\"y\": \"a string\",
\"z\": [
\"element\",
\"second\",
-3
]
}"</pre>
 
=={{header|Erlang}}==