laktak/hjson

JSON for Humans。一种语法宽松、错误较少、注释更多的配置文件格式。

v2.2.2 2023-10-23 19:26 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:04:03 UTC


README

Build Status Packagist

Hjson,人类JSON。为人类设计的配置文件格式。语法宽松,错误较少,注释更多。

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!
}

Hjson的PHP实现基于hjson-js。其他平台请见hjson.github.io

通过composer安装

composer require laktak/hjson

使用方法

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)

此方法将JSON或Hjson文本解析为对象或数组。

  • text:要解析为JSON或Hjson的字符串
  • options:数组
    • keepWsc:布尔值,保留空白和注释。如果您想编辑hjson文件并保留注释,则很有用(默认false)
    • assoc:布尔值,返回关联数组而不是对象(默认false)

HJSONStringifier: stringify($value, $options)

此方法从值生成Hjson文本。

  • value:任何值,通常为对象或数组。
  • options:数组
    • keepWsc:布尔值,保留空白。请参阅解析。
    • bracesSameLine:布尔值,使花括号出现在键名同一行上。默认false。
    • quotes:字符串,控制字符串的显示方式。
      • "min":尽可能不用引号(默认)
      • "always":始终使用引号
    • space:指定嵌套结构的缩进。如果它是数字,则指定每级缩进的空格数。如果它是字符串(如'\t'或 ' '),则包含每级缩进使用的字符。
    • eol:指定EOL序列

修改并保留注释

您可以修改Hjson文件并保留空白和注释。如果应用程序更新其配置文件,则非常有用。

$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);

历史

查看发布版本