Next | Previous

json

Provides APIs for encoding and decoding JSON data. JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. It was derived from the ECMAScript Programming Language Standard. JSON defines a small set of formatting rules for the portable representation of structured data. This implementation complies with RFC 8259.

JSON to Blade value mapping

JSON Blade
Null Nil
String String
Number Number
Boolean Boolean
Array List
Object Dict

Blade to JSON object mapping

Blade JSON
nil Null
Integer Number
Number Number
Char String
String String
List Array
Dict Object
Instance of class implementing to_json() decorator Any
Example,
%> import json
%> json.encode([1, 2, 3])
'[1,2,3]'
%>
%> json.encode({name: 'Blade', version: '0.0.7'})
'{"name":"Blade","version":"0.0.7"}'
%>
%> json.encode({name: 'Blade', version: '0.0.7'}, false)
'{
  "name": "Blade",
  "version": "0.0.7"
}'

Functions

json.encode(value, compact, max_depth)

JSON encodes the given value with a recursive depth up to max_depth.

If compact is true, the resulting json string will be tightly packed. i.e. spaces will be trimmed from objects and arrays. Otherwise, the JSON output will be pretty formatted.

@notes:

  • pretty formatting use 2 spaces instead of tabs.
  • @params:
    • any value

    • bool? compact Default value is true.

    • number? max_depth is the maximum recursive depth for encoding, default = 1024.

  • @returns: string
json.decode(value, allow_comments)

Decodes the input JSON string into Blade objects

  • @params:
    • string value The string to decode

    • bool? allow_comments Can be set to enable/disable C-style comments in json [default = true]

  • @returns: object
json.parse(path)

Parses a file containing json data.

  • @params:
    • string path
  • @returns: object

Classes

class Encoder

Blade to JSON encoding class

.Encoder(compact, max_depth) ➝ Constructor

json.Encoder constructor

@notes:

  • Depth starts from zero
  • Set max_depth to 0 to disable max depth
  • @params:
    • bool? compact Default value is false.

    • number? max_depth Default value is 1024.

.encode(value)

Encodes a value to it's corresponding JSON string.

  • @params:
    • any value
  • @returns: string