public
Last active

Stupid simple JSON parser & generator

  • Download Gist
stupid-json.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
# encoding: utf-8
#
## Stupid small pure Ruby JSON parser & generator.
#
# Copyright © 2013 Mislav Marohnić
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the “Software”), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
# OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
 
require 'strscan'
require 'forwardable'
 
# Usage:
#
# JSON.parse(json_string) => Array/Hash
# JSON.generate(object) => json string
#
# Run tests by executing this file directly. Pipe standard input to the script to have it
# parsed as JSON and to display the result in Ruby.
#
class JSON
def self.parse(data) new(data).parse end
 
WSP = /\s+/
OBJ = /[{\[]/; HEN = /\}/; AEN = /\]/
COL = /\s*:\s*/; KEY = /\s*,\s*/
NUM = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/
BOL = /true|false/; NUL = /null/
 
extend Forwardable
 
attr_reader :scanner
alias_method :s, :scanner
def_delegators :scanner, :scan, :matched
private :s, :scan, :matched
 
def initialize data
@scanner = StringScanner.new data.to_s
end
 
def parse
space
object
end
 
private
 
def space() scan WSP end
 
def endkey() scan(KEY) or space end
 
def object
matched == '{' ? hash : array if scan(OBJ)
end
 
def value
object or string or
scan(NUL) ? nil :
scan(BOL) ? matched.size == 4:
scan(NUM) ? eval(matched) :
error
end
 
def hash
obj = {}
space
repeat_until(HEN) { k = string; scan(COL); obj[k] = value; endkey }
obj
end
 
def array
ary = []
space
repeat_until(AEN) { ary << value; endkey }
ary
end
 
SPEC = {'b' => "\b", 'f' => "\f", 'n' => "\n", 'r' => "\r", 't' => "\t"}
UNI = 'u'; CODE = /[a-fA-F0-9]{4}/
STR = /"/; STE = '"'
ESC = '\\'
 
def string
if scan(STR)
str, esc = '', false
while c = s.getch
if esc
str << (c == UNI ? (s.scan(CODE) || error).to_i(16).chr : SPEC[c] || c)
esc = false
else
case c
when ESC then esc = true
when STE then break
else str << c
end
end
end
str
end
end
 
def error
raise "parse error at: #{scan(/.{1,10}/m).inspect}"
end
 
def repeat_until reg
until scan(reg)
pos = s.pos
yield
error unless s.pos > pos
end
end
 
module Generator
def generate(obj)
raise ArgumentError unless obj.is_a? Array or obj.is_a? Hash
generate_type(obj)
end
alias dump generate
 
private
 
def generate_type(obj)
type = obj.is_a?(Numeric) ? :Numeric : obj.class.name
begin send(:"generate_#{type}", obj)
rescue NoMethodError; raise ArgumentError, "can't serialize #{type}"
end
end
 
ESC_MAP = Hash.new {|h,k| k }.update \
"\r" => 'r',
"\n" => 'n',
"\f" => 'f',
"\t" => 't',
"\b" => 'b'
 
def quote(str) %("#{str}") end
 
def generate_String(str)
quote str.gsub(/[\r\n\f\t\b"\\]/) { "\\#{ESC_MAP[$&]}"}
end
 
def generate_simple(obj) obj.inspect end
alias generate_Numeric generate_simple
alias generate_TrueClass generate_simple
alias generate_FalseClass generate_simple
 
def generate_Symbol(sym) generate_String(sym.to_s) end
 
def generate_Time(time)
quote time.strftime(time.utc? ? "%F %T UTC" : "%F %T %z")
end
def generate_Date(date) quote date.to_s end
 
def generate_NilClass(*) 'null' end
 
def generate_Array(ary) '[%s]' % ary.map {|o| generate_type(o) }.join(', ') end
 
def generate_Hash(hash)
'{%s}' % hash.map { |key, value|
"#{generate_String(key.to_s)}: #{generate_type(value)}"
}.join(', ')
end
end
 
extend Generator
end
 
if __FILE__ == $0
if !$stdin.tty?
data = JSON.parse $stdin.read
require 'pp'
pp data
else
require 'test/unit'
require 'date'
class ParserTest < Test::Unit::TestCase
PARSED = JSON.parse DATA.read
def parsed() PARSED end
def parse_string(str) JSON.parse(%(["#{str}"]).gsub('\\\\', '\\')).first end
def test_string
assert_equal "Pagination library for \"Rails 3\", Sinatra, Merb, DataMapper, and more",
parsed['head']['repository']['description']
end
def test_string_specials
assert_equal "\r\n\t\f\b", parse_string('\r\n\t\f\b')
assert_equal "aA", parse_string('\u0061\u0041')
assert_equal "\e", parse_string('\u001B')
assert_equal "xyz", parse_string('\x\y\z')
assert_equal '"\\/', parse_string('\"\\\\\\/')
assert_equal 'no #{interpolation}', parse_string('no #{interpolation}')
end
def test_hash
assert_equal %w[label ref repository sha user], parsed['head'].keys.sort
end
def test_number
assert_equal 124.3e2, parsed['head']['repository']['size']
end
def test_bool
assert_equal true, parsed['head']['repository']['fork']
assert_equal false, parsed['head']['repository']['private']
end
def test_nil
assert_nil parsed['head']['user']['company']
end
def test_array
assert_equal ["4438f", {"a" => "b"}], parsed['head']['sha']
end
def test_invalid
assert_raises(RuntimeError) { JSON.parse %({) }
assert_raises(RuntimeError) { JSON.parse %({ "foo": }) }
assert_raises(RuntimeError) { JSON.parse %([ "foo": "bar" ]) }
assert_raises(RuntimeError) { JSON.parse %([ ~"foo" ]) }
assert_raises(RuntimeError) { JSON.parse %([ "foo ]) }
assert_raises(RuntimeError) { JSON.parse %([ "foo\\" ]) }
assert_raises(RuntimeError) { JSON.parse %([ "foo\\uabGd" ]) }
end
end
 
class GeneratorTest < Test::Unit::TestCase
def generate(obj) JSON.generate(obj) end
def test_array
assert_equal %([1, 2, 3]), generate([1, 2, 3])
end
def test_bool
assert_equal %([true, false]), generate([true, false])
end
def test_null
assert_equal %([null]), generate([nil])
end
def test_string
assert_equal %(["abc\\n123"]), generate(["abc\n123"])
end
def test_string_unicode
assert_equal %(["ć\\"č\\nž\\tš\\\\đ"]), generate([\"č\nž\tš\\đ"])
end
def test_time
time = Time.utc(2012, 04, 19, 1, 2, 3)
assert_equal %(["2012-04-19 01:02:03 UTC"]), generate([time])
end
def test_date
time = Date.new(2012, 04, 19)
assert_equal %(["2012-04-19"]), generate([time])
end
def test_symbol
assert_equal %(["abc"]), generate([:abc])
end
def test_hash
json = generate(:abc => 123, 123 => 'abc')
assert_match /^\{/, json
assert_match /\}$/, json
assert_equal [%("123": "abc"), %("abc": 123)], json[1...-1].split(', ').sort
end
def test_nested_structure
json = generate(:hash => {1=>2}, :array => [1,2])
assert json.include?(%("hash": {"1": 2}))
assert json.include?(%("array": [1, 2]))
end
def test_invalid_json
assert_raises(ArgumentError) { generate("abc") }
end
def test_invalid_object
err = assert_raises(ArgumentError) { generate("a" => Object.new) }
assert_equal "can't serialize Object", err.message
end
end
end
end
 
__END__
{
"head": {
"ref": "master",
"repository": {
"forks": 0,
"integrate_branch": "rails3",
"watchers": 1,
"language": "Ruby",
"description": "Pagination library for \"Rails 3\", Sinatra, Merb, DataMapper, and more",
"has_downloads": true,
"fork": true,
"created_at": "2011/10/24 03:20:48 -0700",
"homepage": "http://github.com/mislav/will_paginate/wikis",
"size": 124.3e2,
"private": false,
"has_wiki": true,
"name": "will_paginate",
"owner": "dbackeus",
"url": "https://github.com/dbackeus/will_paginate",
"has_issues": false,
"open_issues": 0,
"pushed_at": "2011/10/25 05:44:05 -0700"
},
"label": "dbackeus:master",
"sha": ["4438f", { "a" : "b" }],
"user": {
"name": "David Backeus",
"company": null,
"gravatar_id": "ebe96524f5db9e92188f0542dc9d1d1a",
"location": "Stockholm (Sweden)",
"type": "User",
"login": "dbackeus"
}
}
}
zbenchmark.txt
1 2 3 4 5 6
200 iterations parsing 35kB worth of JSON:
 
user system total real
ruby1.9: 0.320000 0.010000 0.330000 ( 0.329021)
Yajl: 0.240000 0.000000 0.240000 ( 0.236269)
Stupid: 3.960000 0.000000 3.960000 ( 3.973032)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.