{json}
The Smarty {json} function reads JSON data from a file, decodes it and assigns it to a Smarty template variable.
Requirements
Support for json_decode() (PHP version 5.2.0+ or use the PECL extension for older versions)
Parameters
file[ String | required ]
Absolute or relative path (URL) to JSON file.assign[ String | optional ]
Specifies Smarty template variable the parsed JSON data should be assigned to.obj2obj[ Boolean | optional | default:false]
Specifies whether JSON objects should be decoded as either objects or associative arrays (default) in PHP.debug[ Boolean | optional | default:false]
If set totruethe decoded data will be printed in the template.- Variable assign parameters [ String | optional ]
Assigns only one main element/property of the parsed JSON data to the variable (see example). Variable assign parameters may be useful for retrieving only a single branche of nested arrays/objects in cases where one JSON file is used as a configuration file for an entire project.
Examples
Contents of config.json:
{
"months": {
"January": 31,
"February": 28,
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September":30,
"October": 31,
"November": 30,
"December": 31
},
"seasons": [
"spring",
"summer",
"autumn",
"winter"
]
}
Smarty template:
{json file="config.json" assign="year"}
<p>August has {$year.months.August} days.</p>
Convert JSON objects to PHP objects instead of associative arrays:
{json file="config.json" assign="year" obj2obj=true}
<p>August has {$year->months->August} days.</p>
Use a variable assign parameter to assign only a part of the data:
{json file="config.json" mon="months"}
<p>August has {$mon.August} days.</p>
More than one variable assignment parameter can be added. Variable assignment parameters may also be combined with the predefined assign parameter (can't think of a reason to do so though), as long as the value of the assign parameter is not the same as any of the names of the variable assign parameters used.
Downloads
function.json.php (2.31kB)
Installation
Save the downloaded PHP file as function.json.php in your Smarty plugins directory (this is usually the smarty/plugins/ folder).