JSON
JSON reads JSON text into Foundation objects and writes them back
(NSJSONSerialization in shape). Objects become a Map,
arrays an Array, and the scalars a
String, a Number or
Null. From 0.72.
#import "JSON.xc" // not in the Foundation umbrella: import it by nameOverview
Section titled “Overview”try { Map* m = (Map*)JSON.parse(String.withCString("{\"name\":\"xc\",\"tags\":[1,2.5,true,null]}")); String* name = (String*)m.get(String.withCString("name")); Stdio.printf("%s\n", JSON.stringify(m).cString()); // {"name":"xc","tags":[1,2.5,true,null]} }catch (JSONError e) { Stdio.printf("%s\n", e.message().cString()); // bad JSON at byte 12: … }| JSON | Foundation |
|---|---|
| object | Map with String keys, in the order the text has them |
| array | Array |
| string | String, UTF-8, with \u escapes and surrogate pairs decoded |
| number | Number: an int when written without . or an exponent and it fits 64 bits, otherwise a double |
true / false | Number.withBool |
null | Null.null() |
Numbers are exact both ways. An integer keeps all 64 bits. A double is read
correctly rounded and written in the shortest form that reads back as the same
bits, always with a . or an exponent (3.0, 1.0e+300), so it reads back as
a double.
Objects keep their keys in the order the text has them, so a parse and a write give the members back in the same order. A key that appears twice keeps its last value. Nesting deeper than 256 is refused.
Topics
Section titled “Topics”Writing · stringify · stringifyPretty · data
Errors · JSONError
Reading
Section titled “Reading”static Object* parse(String* text) throwsThe value text holds: a Map, Array, String, Number or Null. Any value
may be the root, so "42" parses to a Number. Throws a
JSONError for text that is not one complete JSON value.
parseData
Section titled “parseData”static Object* parseData(Data* data) throwsThe same, from UTF-8 bytes.
Writing
Section titled “Writing”The writers accept the classes above, and write a null reference as null.
They throw a JSONError for anything else: another class, a Map
key that is not a String, a NaN or infinite double (JSON has no spelling for
them), or a String that is not valid UTF-8.
stringify
Section titled “stringify”static String* stringify(Object* v) throwsv as compact JSON: no spaces or newlines.
stringifyPretty
Section titled “stringifyPretty”static String* stringifyPretty(Object* v) throwsv as indented JSON: two spaces a level, "key": value, one member or element a
line, empty containers as {} and [], and a final newline.
{ "a": [ 1, 2 ], "b": {}}static Data* data(Object* v) throwsThe compact text as UTF-8 bytes.
Errors
Section titled “Errors”JSONError
Section titled “JSONError”class JSONError <Error>String* message(void)What the methods throw. A parse error gives the byte offset where reading
stopped, as in bad JSON at byte 4: unterminated array; a write error names
what could not be written, as in JSON: a Set cannot be written as JSON.