Browse | Submit A New Snippet | Create A Package

 

Second simplest json parser in the universe

Type:
Full Script
Category:
Other
License:
Ruby License
Language:
Ruby
 
Description:
This is a json parser for Ruby in one line. See http://www.json.org for details about json.

You can express the full parser using this one line:

null=nil; jsonobj = eval(json.gsub(/(["'])\s*:\s*(['"0-9tfn\[{])/){"#{$1}=>#{$2}"})


LIMITATION: strings with only a : and whitespace will be turned into strings of =>

Versions Of This Snippet::

Cici Wirachmat
Snippet ID Download Version Date Posted Author Delete
625Ruby On Rails2011-11-02 15:17Cici Wirachmat
Changes since last version::
Snippet ID: 199
19942007-02-03 14:23Silvan Golega
Changes since last version::
Please correct or delete this version if I missed something, I am no expert in regular expressions.

The suggested script above didn’t work for me for negative numbers so I adopted the regex to

eval(json.gsub(/(["'])s:s(['"-?0-9tfn[{])/){"#{$1}=>#{$2}"})

Please note the additional -? that allows the missing minus sign.
14932006-04-21 23:27David Pollak
Changes since last version::
Changes since last version::
Made the eval safe. Right now, the code is subject to a code injection attack. See http://dppruby.com/dppsrubyplayground/show/Safe+JSON

Syntax and ease-of-use changes
3512004-03-11 19:03Ralph Mason

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :Ruby On Rails

 Build a SAFE JSON parser
# and execute JSON parsing safely

module SafeJSON
  require 'monitor'
  
  def SafeJSON.build_safe_json
    ret = nil
    waiter = ''
   # waiter.extend(MonitorMixin)
    wait_cond = waiter.new_cond
    
    Thread.start do
      $SAFE = 4
      ret = Proc.new {|json|
        eval(json.gsub(/(["'])\s*:\s*(['"-?0-9tfn\[{])/){"#{$1}=>#{$2}"})
      }
      waiter.synchronize do
        wait_cond.signal
      end
    end
    
    waiter.synchronize do
      wait_cond.wait_while { ret.nil? }
    end
    
    return ret
  end
  
  @@parser = SafeJSON.build_safe_json
  
  # Safely parse the JSON input
  def SafeJSON.parse(input)
    @@parser.call(input)
  rescue SecurityError
    return nil
  end
  
end
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..