Skip to content

Instantly share code, notes, and snippets.

@tkhk
Last active August 29, 2015 14:26
Show Gist options
  • Save tkhk/b04e5b191443c767823f to your computer and use it in GitHub Desktop.
Save tkhk/b04e5b191443c767823f to your computer and use it in GitHub Desktop.

lua の json モジュールは array と object をどのように区別しているのか

lua-users の Json Modules (http://lua-users.org/wiki/JsonModules) の pure lua で書かれてるものを読んでみた.
基本的にはそれぞれ独自に array 判定関数を作っていて, 中身のロジックは大体同様で以下のようなものだった.

  • テーブル内のすべてのキーをチェックする
  • type が number かつ連番であれば, array とみなす
  • 空のテーブルは空のリストとする

cmj-JSON4Lua

http://json.luaforge.net/

tbl = {
  first = {
    1, 2, 3,
  },
  second = {
    aaa = 'vaaa',
    bbb = 'vbbb',
    ccc = 'vccc',
  },
  third = {},
  forth = json.null,
}

json.encode(tbl)
-- {"third":[],"forth":null,"first":[1,2,3],"second":{"bbb":"vbbb","ccc":"vccc","aaa":"vaaa"}}

dkjson

http://dkolf.de/src/dkjson-lua.fsl/

tbl = {
  first = {
    1, 2, 3,
  },
  second = {
    aaa = 'vaaa',
    bbb = 'vbbb',
    ccc = 'vccc',
  },
  third = {},
  forth = json.null,
}

json.encode(tbl)
-- {"third":[],"forth":null,"first":[1,2,3],"second":{"bbb":"vbbb","ccc":"vccc","aaa":"vaaa"}}

jf-JSON

http://regex.info/blog/lua/json

今のところ null を入れる方法がない・・・?

tbl = {
  first = {
    1, 2, 3,
  },
  second = {
    aaa = 'vaaa',
    bbb = 'vbbb',
    ccc = 'vccc',
  },
  third = {},   
  forth = nil,
}
json:encode(tbl)
-- {"first":[1,2,3],"second":{"aaa":"vaaa","bbb":"vbbb","ccc":"vccc"},"third":[]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment