JSON Class
Parse and stringify JSON data. Built with Rust's serde_json for high performance.
JSON.parse(string)
JSON.parse(string)
Parse a JSON string into a Soli value (Hash, Array, String, Int, Float, Bool, or null).
Parameters
string : String - A valid JSON string
Returns
Any - The parsed value
data = JSON.parse('{"name": "Alice", "age": 30}')
println(data["name"]) # "Alice"
numbers = JSON.parse('[1, 2, 3, 4, 5]')
println(numbers[0]) # 1
JSON.stringify(value)
JSON.stringify(value)
Serialize a Soli value to a JSON string.
Parameters
value : Any - A JSON-compatible value (Hash, Array, String, Int, Float, Bool, null)
Returns
String - The JSON string representation
json = JSON.stringify({ "name": "Alice", "scores": [95, 87] })
println(json) # {"name":"Alice","scores":[95,87]}
arr = JSON.stringify([1, 2, 3])
println(arr) # [1,2,3]
<script>.
A </script> in any string value ends the element — the
HTML tokenizer does not care that it sits inside a JSON string — and
everything after it is parsed as markup. Use
json_script() there.
json_script(value)
Serialize a Soli value to JSON that is safe to embed in an HTML <script> body.
<, > and & become \uXXXX escapes, along with U+2028 and U+2029 (valid in JSON, but line terminators in JavaScript source). A JSON parser reads those escapes back as the original characters, so the value a script receives is unchanged; what changes is that nothing in the output can end the element or be reinterpreted by the HTML parser.
Parameters
value : Any - A JSON-compatible value
Returns
String - JSON with the HTML-significant characters escaped
<script>
window.__data = <%- json_script(post) %>;
</script>
j() is not an alternative here: it is an HTML escape, so it turns & into & inside the JSON and corrupts the data.
JSON.parse_jsonp(string)
JSON.parse_jsonp(string)
Unwrap a JSONP callback({...}); string (with an optional leading /**/ guard) and parse the inner JSON into a Soli value. Pairs with HTTP.get_jsonp for consuming legacy cross-origin APIs.
Parameters
string : String - A JSONP response body
Returns
Any - The parsed value. Raises if the string is not a valid callback(...) wrapper or the inner JSON is malformed.
data = JSON.parse_jsonp('/**/cb({"name": "Alice", "age": 30});')
println(data["name"]) # "Alice"
Common Patterns
Reading and Writing JSON Files
# Read JSON file
config = JSON.parse(slurp("config.json"))
println(config["database"]["host"])
# Write JSON file
data = { "users": [{ "name": "Alice" }] }
barf("data.json", JSON.stringify(data))