Libdjson
Creator: |
Contents
- 1 Overview
- 2 Examples
- 3 ToDo
- 4 Documentation
- 4.1 JSONObject readJSON(char[] src);
- 4.2 class JSONError: object.Exception;
- 4.3 abstract interface JSONType;
- 4.4 class JSONObject: libdjson.json.JSONType;
- 4.5 class JSONArray: libdjson.json.JSONType;
- 4.6 class JSONString: libdjson.json.JSONType;
- 4.7 class JSONBoolean: libdjson.json.JSONType;
- 4.8 class JSONNull: libdjson.json.JSONType;
- 4.9 class JSONNumber: libdjson.json.JSONType;
- 4.10 char[] JSONEncode(char[] src);
- 4.11 char[] JSONDecode(char[] src);
- 4.12 char[] quickUTF8(dchar dachar);
Overview
This is a basic JSON parser written in D. It currently supports building JSON structures in code and reading them from a piece of text, as well as outputting those structures to JSON text. It is available from my SVN server.
Examples
Traversing a node tree with known structure is now fairly simple. As seen, foreach is possible over JSON objects and JSON arrays without explicit casting, since it is now part of the interface. If you try to foreach over something that isn't a container, you get an exception.
foreach(obj;jstr.readJSON()["phoneNumbers"]) { writefln("Got " ~ obj["type"].toJSONString.get ~ " phone number:" ~ obj["number"].toJSONString.get); }
Creation of a JSON object from scratch:
auto root = new JSONObject(); auto arr = new JSONArray(); arr ~= new JSONString("da blue teeths!\"\\"); root["what is that on your ear?"] = arr; root["my pants"] = new JSONString("are on fire"); root["i am this many"] = new JSONNumber(10.253); root["blank"] = new JSONObject();
Parsing of a string into a JSON object tree and access of resulting tree:
string jstr = "{\"firstName\": \"John\",\"lastName\": \"Smith\",\"address\": {\"streetAddress\": \"21 2nd Street\",\"city\": \"New York\",\"state\": \"NY\",\"postalCode\": 10021},\"phoneNumbers\": [{ \"type\": \"home\", \"number\": \"212 555-1234\" },{ \"type\": \"fax\", \"number\": \"646 555-4567\" }],\"newSubscription\": false,\"companyName\": null }"; // this should create a functionally equivalent string...always jstr = jstr.readJSON().toString; // the JSON can also be output in a prettified manner so as to be more readable (and is also functionally equivalent) writef("Output using toPrettyString:\n"~jstr.readJSON().toPrettyString~"\nEnd pretty output\n"); auto jobj = jstr.readJSON(); writef("Unit Test libDJSON JSON access...\n"); writef("Got first name:" ~ jobj["firstName"].toJSONString.get ~ "\n"); writef("Got last name:" ~ jobj["lastName"].toJSONString.get ~ "\n"); // you can run a foreach over the objects foreach(obj;jobj["phoneNumbers"]) { writef("Got " ~ obj["type"].toJSONString.get ~ " phone number:" ~ obj["number"].toJSONString.get ~ "\n"); }
ToDo
- Build some kind of query system so that it is easier to pull data out of the JSON object.
- XPath inspired?, may always have to return an array of nodes
Documentation
LibDJSON contains functions and classes for reading, parsing, and writing JSON documents.
Authors: William K. Moore, III
License: Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:
The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Standards: Attempts to conform to the subset of Javascript required to implement the JSON Specification.
JSONObject readJSON(char[] src);
- Read an entire string into a JSON tree.
-
- Example:
- auto root = new JSONObject();
- auto arr = new JSONArray();
- arr ~= new JSONString("da blue teeths!\"\\");
- root["what is that on your ear?"] = arr;
- root["my pants"] = new JSONString("are on fire");
- root["i am this many"] = new JSONNumber(10.253);
- string jstr = root.toString;
- writef("Unit Test libDJSON JSON creation...\n");
- writef("Generated JSON string: ");writef(jstr);writef("\n");
- writef("Regenerated JSON string: ");writef(readJSON(jstr).toString);writef("\n");
- Returns:
- A JSONObject with no name that is the root of the document that was read.
- Throws:
- JSONError on any parsing errors.
class JSONError: object.Exception;
- An exception thrown on JSON parsing errors.
abstract interface JSONType;
- This is the interface implemented by all classes that represent JSON objects.
- abstract void parse(ref char[] source);
- The parse method of this interface should ALWAYS be destructive, removing things from the front of source as it parses.
- abstract JSONObject toJSONObject();
- Convenience function for casting to JSONObject.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONArray toJSONArray();
- Convenience function for casting to JSONArray.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONString toJSONString();
- Convenience function for casting to JSONString.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONBoolean toJSONBoolean();
- Convenience function for casting to JSONBoolean.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONNumber toJSONNumber();
- Convenience function for casting to JSONNumber.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONNull toJSONNull();
- Convenience function for casting to JSONNull.
- Returns
- The casted reference or null on a failed cast.
- abstract JSONType opIndex(char[] key);
- Associative array index function for objects describing associative array-like attributes.
- Returns
- The chosen index or a null reference if the index does not exist.
- abstract int opApply(int delegate(char[], JSONType) dg);
- Allow foreach over the object with string key.
- abstract int opApply(int delegate(char[], ref JSONType) dg);
- Allow foreach over the object with string key and ref value.
- abstract JSONType opIndex(int key);
- Array index function for objects describing array-like attributes.
- Returns
- The chosen index or a null reference if the index does not exist.
- abstract int opApply(int delegate(int, JSONType) dg);
- Allow foreach over the object with integer key.
- abstract int opApply(int delegate(int, ref JSONType) dg);
- Allow foreach over the object with integer key and ref value.
- abstract int opApply(int delegate(JSONType) dg);
- Convenience function for iteration that apply to both AA and array type operations
- abstract int opApply(int delegate(ref JSONType) dg);
- Convenience function for iteration that apply to both AA and array type operations with ref value
class JSONObject: libdjson.json.JSONType;
- JSONObject represents a single JSON object node and has methods for adding children. All methods that make changes modify this JSONObject rather than making a copy, unless otherwise noted. Many methods return a self reference to allow cascaded calls.
- this();
- Nothing to see here except for the boring constructor, move along.
- void opIndexAssign(JSONType type, char[] key);
- Operator overload for setting keys in the AA.
- JSONType opIndex(char[] key);
- Operator overload for accessing values already in the AA.
- Returns
- The child node if it exists, otherwise null.
- int length();
- Allow the user to get the number of elements in this object
- Returns
- The number of child nodes contained within this JSONObject
- int opApply(int delegate(JSONType) dg);
- Operator overload for foreach iteration through the object with values only
- int opApply(int delegate(ref JSONType) dg);
- Operator overload for foreach iteration through the object with values only and allow modification of the reference
- int opApply(int delegate(char[], JSONType) dg);
- Operator overload for foreach iteration through the object with key and value
- int opApply(int delegate(char[], ref JSONType) dg);
- Operator overload for foreach iteration through the object with key and value and allow modification of the reference
- char[] toString();
- A method to convert this JSONObject to a user readable format.
- Returns
- A JSON string representing this object and it's contents.
- void parse(ref char[] source);
- This function parses a JSONObject out of a string
class JSONArray: libdjson.json.JSONType;
- JSONArray represents a single JSON array, capable of being heterogenous
- this();
- Nothing to see here, move along.
- void opCatAssign(JSONType child);
- Operator overload to allow addition of children
- JSONType opIndex(int key);
- Operator overload to allow access of children
- Returns
- The child node if it exists, otherwise null.
- int length();
- Allow the user to get the number of elements in this object
- Returns
- The number of child nodes contained within this JSONObject
- int opApply(int delegate(JSONType) dg);
- Operator overload for foreach iteration through the array with values only
- int opApply(int delegate(ref JSONType) dg);
- Operator overload for foreach iteration through the array with values only and allow modification of the reference
- int opApply(int delegate(int, JSONType) dg);
- Operator overload for foreach iteration through the array with key and value
- int opApply(int delegate(int, ref JSONType) dg);
- Operator overload for foreach iteration through the array with key and value and allow modification of the reference
- char[] toString();
- A method to convert this JSONArray to a user readable format.
- Returns
- A JSON string representing this object and it's contents.
- void parse(ref char[] source);
- This function parses a JSONArray out of a string
class JSONString: libdjson.json.JSONType;
- JSONString represents a JSON string. Internal representation is escaped for faster parsing and JSON generation.
- this();
- The boring default constructor.
- this(string data);
- The ever so slightly more interesting initializing constructor.
- void set(char[] data);
- Allow the data to be set so the object can be reused.
- char[] get();
- Allow the data to be retreived.
- char[] toString();
- A method to convert this JSONString to a user readable format.
- Returns
- A JSON string representing this object and it's contents.
- void parse(ref char[] source);
- This function parses a JSONArray out of a string and eats characters as it goes, hence the ref string parameter.
class JSONBoolean: libdjson.json.JSONType;
- JSONBoolean represents a JSON boolean value.
- this();
- The boring constructor, again.
- this(bool data);
- Only a bit of input for this constructor.
- void set(bool data);
- Allow setting of the hidden bit.
- bool get();
- Allow the bit to be retreived.
- char[] toString();
- A method to convert this JSONBoolean to a user readable format.
- Returns
- A JSON string representing this object and it's contents.
- void parse(ref char[] source);
- This function parses a JSONBoolean out of a string and eats characters as it goes, hence the ref string parameter.
class JSONNull: libdjson.json.JSONType;
- JSONNull represents a JSON null value.
- this();
- You're forced to use the boring constructor here.
- char[] toString();
- A method to convert this JSONNull to a user readable format.
- Returns
- "null". Always. Forever.
- void parse(ref char[] source);
- This function parses a JSONNull out of a string. Really, it just rips "null" off the beginning of the string and eats whitespace.
class JSONNumber: libdjson.json.JSONType;
- JSONNumber represents any JSON numeric value.
- this();
- Another boring constructor...
- this(real data);
- ...and its slightly less boring sibling.
- void set(real data);
- Allow setting of the hidden number.
- real get();
- Allow the number to be retreived.
- char[] toString();
- A method to convert this JSONNumber to a user readable format.
- Returns
- A JSON string representing this number.
- void parse(ref char[] source);
- This function parses a JSONNumber out of a string and eats characters as it goes, hence the ref string parameter.
char[] JSONEncode(char[] src);
- Perform JSON escapes on a string
- Returns
- A JSON encoded string
char[] JSONDecode(char[] src);
- Unescape a JSON string
- Returns
- A decoded string.
char[] quickUTF8(dchar dachar);
- This probably needs documentation. It looks like it converts a dchar to the necessary length string of chars.