JSON-Encoding and Decoding Methods (json)
To enable these methods, add 'json' to DataMapper's config, under 'extensions'.
Converts objects to and from a JSON-encoded string.
to_json($fields, $pretty_print, $include)
- $fields: (Optional) If provided, only these fields will be included. If empty or not provided, only the database columns will be included.
- $pretty_print: (Optional) If TRUE, the JSON string will be formatted to be easier to read. Defaults to FALSE.
- $include: (Optional) an array of related object names (with deep relation support) that needs to be included in the result. Defaults to array().
- Returns: A JSON-encoded view of the $object, or FALSE if an error occurs.
Converts the $object into a JSON-encoded string.
Usage
$u = new User(); $u->get_by_id($user_id); $u->set_json_content_type(); echo $u->to_json(array('id', 'name', 'email'), TRUE); // Outputs something like // {"id": 1, "name":"Bob Johnson", "email":"bob.johnson@example.com"} // Include the related groups in the result $u = new User(); $u->get_by_id($user_id); $u->group->get(); $u->set_json_content_type(); echo $u->to_json(array('id', 'name', 'email'), FALSE, array('group')); // Outputs something like // {"id": 1, "name":"Bob Johnson", "email":"bob.johnson@example.com", "group":"[{\"id\":1,\"name\":\"Administrators\"}]"}
all_to_json($fields, $pretty_print, $include)
- $fields: (Optional) If provided, only these fields will be included. If empty or not provided, only the database columns will be included.
- $pretty_print: (Optional) If TRUE, the JSON string will be formatted to be easier to read. Defaults to FALSE.
- $include: (Optional) an array of related object names (with deep relation support) that needs to be included in the result. Defaults to array().
- Returns: A JSON-encoded view of $object->all, or FALSE if an error occurs.
Converts $object->all into a JSON-encoded string. The items will be placed into an array before conversion.
from_json($json, $fields)
- $json: The JSON-encoded string to save back to the object.
- $fields: (Optional) If provided, only these fields will be saved. If empty or not provided, only the database columns will be saved.
- Returns: TRUE on success, FALSE if the string conversion failed.
Stores values encapsulated in a JSON-encoded string back on the $object.
Usage
$json = $this->input->post('notedata'); $n = new Note(); if($n->from_json($json)) { // TODO: verify input, save changes } else { show_error('Invalid input'); }
set_json_content_type()
A simple method used to set the proper content type header (“Content-Type: application/json”) for JSON files.