A lightweight H/JSON library for Lua
Ported from hjson-py. Inspired by rxi - json.lua.
- Implemented in pure Lua: tested with Lua 5.3 and 5.4
luarocks install hjson-lua- drop hjson.lua and hjson folder folder into your project
- require hjson.lua
hjson = require "hjson"
Library exports json.lua like and JS like api.
- Lua object to HJSON - returns HJSON string
encode(obj, options)stringify(obj, options)- Parameters:
obj- Lua object -table,string,number,nil,booleanoptionstable with following values:indent- default" ". Accepts string of whitespace characters or a number representing number of spaces (non indented HJSON is JSON, automatically forwards to_to_jsonversion)skip_keys- defaulttrueSkips invalid keys. If false throws error on invalid key.- Valid key types:
boolean,nil,string
- Valid key types:
sort_keys- whether to sort keys in objectsitem_sort_key- sort function which is passed totable.sortsorting object keysinvalid_objects_as_typeif true functions and others objects are replaced with their type name in format__lua_<type>e.g.__lua_function
- Lua object to JSON - returns JSON string
encode(obj, options)stringify(obj, options)- Parameters:
obj- Lua object -table,string,number,nil,booleanoptionstable with following values:indent- default" ". Accepts string of whitespace characters or a number representing number of spaces (non indented HJSON is JSON, automatically forwards to_to_jsonversion)skip_keys- defaulttrueSkips invalid keys. If false throws error on invalid key.- Valid key types:
boolean,nil,string
- Valid key types:
sort_keys- whether to sort keys in objectsitem_sort_key- sort function which is passed totable.sortsorting object keysinvalid_objects_as_typeif true functions and others objects are replaced with their type name in format__lua_<type>e.g.__lua_function
- H/JSON to Lua object - returns Lua object
decode(str, strict, object_hook, object_pairs_hook)parse(str, strict, object_hook, object_pairs_hook)- Parameters:
strhas to be valid HJSON stringstrictdefaulttrue. If true parse/decode fails on invalid control characters.object_hook-function(obj)hook which allows to adjust tables generated from JSON on per JSON object basis (including nested objects).objis luatable.object_pairs_hook-function(pairs)hook which allows to adjust table before generation.pairsis table (in array form) composited fromkey/valuepairs. It is called before the table forobject_hookis generated.
null values contained within an array or object are converted to nil and are therefore lost upon decoding.
This library is free software; you can redistribute it and/or modify it under the terms of the MIT license. See LICENSE for details.