Hjson for PHP

Overview

hjson-php

Build Status Packagist

Hjson, the Human JSON. A configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.

Hjson Intro

{
  # specify rate in requests/second (because comments are helpful!)
  rate: 1000

  // prefer c-style comments?
  /* feeling old fashioned? */

  # did you notice that rate doesn't need quotes?
  hey: look ma, no quotes for strings either!

  # best of all
  notice: []
  anything: ?

  # yes, commas are optional!
}

The PHP implementation of Hjson is based on hjson-js. For other platforms see hjson.github.io.

Install from composer

composer require laktak/hjson

Usage

use HJSON\HJSONParser;
use HJSON\HJSONStringifier;

$parser = new HJSONParser();
$obj = $parser->parse(hjsonText);

$stringifier = new HJSONStringifier;
$text = $stringifier->stringify($obj);

API

HJSONParser: parse($text, $options)

This method parses JSON or Hjson text to produce an object or array.

  • text: the string to parse as JSON or Hjson
  • options: array
    • keepWsc: boolean, keep white space and comments. This is useful if you want to edit an hjson file and save it while preserving comments (default false)
    • assoc: boolean, return associative array instead of object (default false)

HJSONStringifier: stringify($value, $options)

This method produces Hjson text from a value.

  • value: any value, usually an object or array.
  • options: array
    • keepWsc: boolean, keep white space. See parse.
    • bracesSameLine: boolean, makes braces appear on the same line as the key name. Default false.
    • quotes: string, controls how strings are displayed.
      • "min": no quotes whenever possible (default)
      • "always": always use quotes
    • space: specifies the indentation of nested structures. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level.
    • eol: specifies the EOL sequence

modify & keep comments

You can modify a Hjson file and keep the whitespace & comments intact. This is useful if an app updates its config file.

$parser = new HJSONParser;
$stringifier = new HJSONStringifier;

$text = "{
  # specify rate in requests/second (because comments are helpful!)
  rate: 1000

  // prefer c-style comments?
  /* feeling old fashioned? */

  # did you notice that rate doesn't need quotes?
  hey: look ma, no quotes for strings either!

  # best of all
  notice: []
  anything: ?

  # yes, commas are optional!

  array: [
    // hello
    0
    1
    2
  ]
}";

// Parse, keep whitespace and comments
$data = $parser->parseWsc($text);

// Modify like you normally would
$data->rate = 500;

// You can also edit comments by accessing __WSC__
$wsc1 = &$data->__WSC__; // for objects
$wsc2 = &$data->array['__WSC__']; // for arrays

// __WSC__ for objects contains { c: {}, o: [] }
// - c with the actual comment and, firts comment is key ' '
// - o (array) with the order of the members
$emptyKey = " ";
$wsc1->c->$emptyKey = "\n  # This is the first comment";
$wsc1->c->rate = "\n  # This is the comment after rate";

// Sort comments order just because we can
sort($wsc1->o);

// Edit array comments
$wsc2[0] .= ' world';

// convert back to Hjson
$text2 = $stringifier->stringifyWsc($data);

History

see releases

Comments
  • PHP 5.6 and 7.0 EOL

    PHP 5.6 and 7.0 EOL

    PHP versions 5.6 and 7.0 are officially unsupported now. Should we stop supporting them as well?

    In my PR #19, I made some changes to be compatible with the latest versions of PHP and phpunit, but it broke PHP 7.0 and 5.6 compatibility. It would be easier overall to stop supporting the older versions, but I don't know, is anyone still using this library with an old PHP version?

    opened by dqsully 11
  • Fix issue #11 and test enhancement

    Fix issue #11 and test enhancement

    Changed log

    • Fix issue #11.
    • It's related to this PR #12.
    • Create this PR because the PR #12 seems to be inactive.
    • Upgrade the PHPUnit version and support the multiple PHP versions in Travis CI build.
    • To be compatible with the stable PHPUnit version, using the class-based PHPUnit namespace.
    • Add the ext-mbstring in require key because the mb_strlen function is used in this repository.
    opened by peter279k 7
  • Cirillic chars in comments breaks script

    Cirillic chars in comments breaks script

    Throws different errors...

    Fatal error: Uncaught HJSON\HJSONException: End of input while parsing an array (did you forget a closing ']'?) at line 19, 30 >>>9,

    opened by 4cc355-d3n13d 7
  • Fix utf8 implementation

    Fix utf8 implementation

    Fixes #14

    It looks like everything was built with utf8 strings in mind, but the parser implementation always counted in bytes, not characters. With this fix, $this->ch can now be a multi-byte utf8 character, but $this->at still counts up bytes. I've hopefully fixed the next(), peek(), and error(), and I think that's all that needs to be fixed, but I would like someone else to go over my changes as well.

    Something to note about this code is that the php function mb_substr counts in characters whereas mb_strcut counts (safely) in bytes. So in several places I will use mb_substr(mb_strcut($str, $pos), 0, $len) where $pos is in bytes and $len is in characters.

    opened by dqsully 5
  • Add () when instantiating the class to follow PER standard

    Add () when instantiating the class to follow PER standard

    Add the () in the constructor call for consistency (and follow PHP standards too).

    Reference to the standard: https://www.php-fig.org/per/coding-style/#4-classes-properties-and-methods.

    opened by s-patompong 4
  •  { :0 } causes Fatal Error

    { :0 } causes Fatal Error

    {
      :0
    }
    

    causes Fatal error: Cannot access empty property in .../src/HJSON/HJSONParser.php on line 204 instead of a exception with message Error: Found ':' but no key name

    opened by luizbills 4
  • String fails in PHP but not in js

    String fails in PHP but not in js

    Thank you for a great library.

    I found an issue. The string

    {products: [
      {name:'Knife', price: 2.25},
      {name:'Spoon', price: 2.50},
      {name:'Fork', price: 2.99},
    ]}
    

    works when I use http://hjson.org/try.html but not when using this library.

    opened by mathiasrw 3
  • Incorrect stringification of falsy strings

    Incorrect stringification of falsy strings

    HJSONStringifier->quote has a check at the beginning which returns an empty quoted string if the string is falsy:

    private function quote($string = null, $gap = null, $hasComment = null, $isRootObject = null)
        {
            if (!$string) {
                return '""';
            }
    ...}
    

    This means that if the string is falsy, such as if it contains just "0", it won't be serialized correctly:

    php > echo (new HJSON\HJSONStringifier)->stringify(["A", "0"]);
    [
      A
      ""
    ]
    

    The fix is simply changing the !$string test to $string === ''. As HJSONStringifier->quote is a private function and, as far as I can see, there is no way for it to be called with anything other than a string, this should not affect anything else.

    opened by andvaranaut 1
  • UTF-8 in multiline strings bug

    UTF-8 in multiline strings bug

    This example code:

    $hjsonParser->parse(
    	'{
    		content:
    			\'\'\'
    			←→±≠Я
    			\'\'\'
    	}'
    );
    

    Throws:

    Bad multiline string at line 5, 1 >>> ''' } ...
    
    opened by Ronef 1
  • Can't install with composer

    Can't install with composer

    PS C:\xampp\htdocs\ulicms> composer require HJSON/HJSON
    
    
      [InvalidArgumentException]
      Could not find package HJSON/HJSON at any version for your minimum-stability (stable). Check the package spelling or
       your minimum-stability
    

    I tried this but got the same error

    {
    	"minimum-stability" : "dev"
    }
    
    opened by derUli 1
  • Parse failed with

    Parse failed with "0" char in multiline string

    Hi, Cannot have any kind and anywhere the "0" (zero) char in a multiline string. it does give me each time: HJSONException: Bad multiline string at line x, y

    Other "numbers" are working fine :-) Thanks

    opened by TigersWay 1
  • Disable Hash (#) comments

    Disable Hash (#) comments

    Hi, could you please provide an option to completely disable using hash (#) as a special symbol for comments?

    '#' is a widespread symbol among the web and it is not convenient to enclose a string in quotes should it start with hash.

    Thanks.

    opened by MerryPanda 0
  • Contributor Wanted!

    Contributor Wanted!

    The PHP implementation of Hjson was kindly contributed by @iainhallam and @jawb.

    As they are occupied elsewhere we are in need of a contributor. If you know PHP and would like to help out please let us know!

    help wanted 
    opened by laktak 5
Releases(v2.2.0)
Owner
Hjson
A user interface for JSON.
Hjson
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 272 Dec 22, 2022
PHP Meminfo is a PHP extension that gives you insights on the PHP memory content

MEMINFO PHP Meminfo is a PHP extension that gives you insights on the PHP memory content. Its main goal is to help you understand memory leaks: by loo

Benoit Jacquemont 994 Dec 29, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 258 Sep 15, 2022
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

appserver.io 951 Dec 25, 2022
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
A PHP 5.3+ and PHP 7.3 framework for OpenGraph Protocol

Opengraph Test with Atoum cd Opengraph/ curl -s https://getcomposer.org/installer | php php composer.phar install --dev ./vendor/atoum/atoum/bin/atoum

Axel Etcheverry 89 Dec 27, 2022
A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch screens with a resolution of 1024x600 connected to a Raspberry Pi.

EDStatusPanel A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch scr

marcus-s 24 Oct 4, 2022
🐘 A probe program for PHP environment (一款精美的 PHP 探針, 又名X探針、劉海探針)

Simplified Chinese | 简体中文 Traditional Chinese(Taiwan) | 正體中文(臺灣) Traditional Chinese(Hong Kong) | 正體中文(香港) Japanese | 日本語 ?? X Prober This is a probe

Km.Van 1.2k Dec 28, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
PHP generics written in PHP

PHP generics written in PHP Require PHP >= 7.4 Composer (PSR-4 Autoload) Table of contents How it works Quick start Example Features Tests How it work

Anton Sukhachev 173 Dec 30, 2022
PHP exercises from my course at ETEC and some of my own play-around with PHP

etec-php-exercises PHP exercises from my course at ETEC and some of my own play-around with PHP Translations: Português (BR) Projects Project Descript

Luis Felipe Santos do Nascimento 6 May 3, 2022
GitHub action to set up PHP with extensions, php.ini configuration, coverage drivers, and various tools.

GitHub action to set up PHP with extensions, php.ini configuration, coverage drivers, and various tools.

Shivam Mathur 2.4k Jan 6, 2023
php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

youyiio 5 Aug 15, 2022
Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Ry-Zen 7 Aug 21, 2022
Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API.

Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API. Check out the latest API documentation. Add library in a composer.json file.

Patrick Falize 6 Oct 7, 2021
churn-php is a package that helps you identify php files in your project that could be good candidates for refactoring

churn-php Helps discover good candidates for refactoring. Table of Contents What Is it? Compatibility How to Install? How to Use? How to Configure? Si

Bill Mitchell 1.3k Dec 22, 2022
Run your WP site on github pages, php innovation award winner https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html

Gitpress Run wordpress directly on github pages Gitpress won the innovation award for may 2021 Read more about this https://naveen17797.github.io/gitp

naveen 13 Nov 18, 2022
A pure PHP implementation of the MessagePack serialization format / msgpack.org[PHP]

msgpack.php A pure PHP implementation of the MessagePack serialization format. Features Fully compliant with the latest MessagePack specification, inc

Eugene Leonovich 368 Dec 19, 2022
SublimeLinter 3 plugin for PHP, using php -l.

SublimeLinter-php This linter plugin for SublimeLinter provides an interface to php -l. It will be used with files that have the "PHP", "HTML", or "HT

null 205 Jan 4, 2023