LoginSignup
25
22

More than 5 years have passed since last update.

RubyでHjsonパーサを書いた

Last updated at Posted at 2016-08-14

最近触っているソフトウェアは立て続けに設定をjsonを書かせるものばかりで辟易としていたところに、何かまともなものはないかと調べていたらhjsonというものがあった。

better JSON的なノリで作られたもののようだが、考案者自身がRFCも書いているなど、なかなかやる気に満ち溢れているように見える。

ところが残念なことに、自分が発見した時点ではruby製のhjsonパーサがまだ存在していなかったため、サクッと書いてみたので記事も書く。

namusyaka/hjson

使い方

基本的にHjson.parseしか使わない前提。

require 'hjson'

hjson = <<HJSON
// for your config
// use #, // or /**/ comments,
// omit quotes for keys
key: 1
// omit quotes for strings
string: contains everything until LF
// omit commas at the end of a line
cool: {
  foo: 1
  bar: 2
}
// allow trailing commas
list: [
  1,
  2,
]
// and use multiline strings
realist:
  '''
  My half empty glass,
  I will fill your empty half.
  Now you are half full.
  '''
HJSON

Hjson.parse(hjson)

Hjsonの文法いろいろ

せっかくなので、Hjsonの文法について実際のコード例を挙げながら説明したい。

Comments

一番魅力的なのはやはりJSON中にコメントが書ける、というところだろうか。

require 'hjson'

hjson =<<HJSON
{
  # specify rate in requests/second
  "rate": 1000

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

Hjson.parse(hjson) #=> {"rate"=>1000}

Quotes

キー名はquoteで囲まなくて良い。

require 'hjson'

hjson =<<HJSON
{
  key: "value"
}
HJSON

Hjson.parse(hjson) #=> {"key"=>"value"}

Commas

末尾の,は省略可能。

require 'hjson'

hjson =<<HJSON
{
  one: 1
  two: 2
  three: 4 # oops
}
HJSON

Hjson.parse(hjson) #=> {"one"=>1, "two"=>2, "three"=>4}

Quoteless

valueに値する部分もquoteを省略でき、その場合は文字列としてパースする。

require 'hjson'

hjson =<<HJSON
{
  text: look ma, no quotes!

  # To make your life easy, put the next
  # value or comment on a new line.
  # It's also easier to read!
}
HJSON

Hjson.parse(hjson) #=> {"text"=>"look ma, no quotes!"}

Escapes

エスケープ不要。

require 'hjson'

hjson = <<HJSON
{
  # write a regex without escaping the escape
  regex: ^\d*\.{0,1}\d+$

  # quotes in the content need no escapes
  inject: <div class="important"></div>

  # inside quotes, escapes work
  # just like in JSON
  escape: "\\\\ \n \t\\""
}
HJSON

Hjson.parse(hjson)
#=> {"regex"=>"^d*.{0,1}d+$",
 "inject"=>"<div class=\"important\"></div>",
 "escape"=>"\\ \n \t\""}

Multiline

'''を用いることで複数行の文字列をわかりやすく書ける。

require 'hjson'

hjson =<<HJSON
{
  haiku:
    '''
    JSON I love you.
    But strangled is my data.
    This, so much better.
    '''
}
HJSON

Hjson.parse(hjson) #=> {"haiku"=>"JSON I love you.\nBut strangled is my data.\nThis, so much better."}

Braces

rootオブジェクトについては{}を省略できる。

require 'hjson'

hjson =<<HJSON
// this is a valid config file
joke: My backslash escaped!
HJSON

Hjson.parse(hjson) #=> {"joke"=>"My backslash escaped!"}

おわりに

JSONと完全に互換性があり、validなJSONはHjsonとしてもvalidである。
したがって、導入する分にはハードルも高くないので、試してみるのも面白いかもしれない。

25
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
22