JSON¶
This example shows how to use our eni_json.so to parse JSON.
eni_json.so is relatively low-level, so a json.lity library is provided.
Usage¶
json.lity defines the functions to interface with the low level eni library.
Here’s an example that is equivalent to string = data[1][0] in python or javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 | pragma lity ^1.2.4;
import "./json.lity";
contract Test {
using JSON for JSON.ValueRef;
function main(string raw) pure public returns(string) {
JSON.ValueRef memory root = JSON.newValueRef(raw);
JSON.ValueRef memory a1 = root.arrayGet(raw, 1);
string memory a1_0 = a1.arrayGet(raw, 0).asString(raw);
return a1_0;
}
}
|
- Line 3:
importto use - Line 6: the
usingkeyword can be used to ease programming: we can writea1_0.asString(raw)instead ofJSON.asString(a1_0, raw) - Line 8: the JSON library does not store copies of parsed objects in memory, instead, they store references (
byteranges) to the raw JSON string.JSON.newValueRefhelps initializing aJSON.ValueReffor the entire raw JSON string. - Line 9:
arrayGetcan be used to get a value by index get in an array. - Line 10:
asStringcan be used to parse a JSON value as a string.
ValueRef¶
Note
The definition of the ValueRef struct should be treated as an implementation detail.
Users should only use the asType() and containerGet() methods on ValueRef.
A ValueRef currently stores two units, which are the first byte and the last+1 byte of the JSON value.
struct ValueRef {
uint begin;
uint end;
}
API Reference¶
-
JSON.newValueRef(rawJSON)¶ Returns: JSON.ValueRef Creates a new
JSON.ValueRefthat references the root JSON value ofrawJSON.The behavior is undefined if the rawJSON is not a valid JSON value.
-
valueRef.getType(rawJSON)¶ Returns: JSON.Type (enum) Returns type type of the value referenced by
valueRef.Supported types JSON.Type.BOOLJSON.Type.NUMBERJSON.Type.STRINGJSON.Type.ARRAYJSON.Type.OBJECTJSON.Type.INVALID
-
valueRef.asBool(rawJSON)¶ Returns: bool Returns the
boolvalue referenced byvalueRef.The behavior is undefined if the value is not a
JSON.Type.BOOL.
-
valueRef.asInt(rawJSON)¶ Returns: int Returns the
intvalue referenced byvalueRef.The behavior is undefined if the value is not a
JSON.Type.NUMBER.If the value is a floating point number, it is rounded down.
-
valueRef.asString(rawJSON)¶ Returns: string Returns the
stringvalue referenced byvalueRef.The behavior is undefined if the value is not a
JSON.Type.STRING.
-
valueRef.arrayGet(rawJSON, index)¶ Returns: JSON.ValueRef Returns the reference to
valueRef[index].The behavior is undefined if the index is out of the bounds of the array referenced by
valueRefor ifvalueRefis not aJSON.Type.ARRAY.
-
valueRef.objectGet(rawJSON, key)¶ Returns: JSON.ValueRef Returns the reference to
valueRef[key].The behavior is undefined if the key does not exist on the object referenced by
valueRefor ifvalueRefis not aJSON.Type.OBJECT.