The Ruby language is widely used and can be used in a simple and flexible way to help us implement many functional requirements. Ruby parses Json in a very simple way.
- Ruby special syntax concepts
- Example of Ruby code for getting the current class name
- Ruby module OpenURI to get http/FTP address content
- Analysis of Ruby encryption implementation code examples
- Ruby blocks provides flexible encoding methods
Example of Json parsing IN Ruby:
- Json = '["a", "B", "C"]'
- Puts "Unsafe # {unsafe_json
(Json). inspect }"
- # Output Unsafe
["A", "B", "C"]
Ruby parses Json to parse the preceding json string into an Array. This method is not safe, for example:
- json = 'puts "Danger
Will Robinson"'
- puts "Unsafe #{unsafe_json
(json).inspect}"
What should I output? Unfortunately, nothing can be parsed. A warning is displayed: warning: character class has '[' without escape security method is as follows:
- 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
With this Module, you can use Ruby to parse Json:
- Using les = SafeJSON. parse ('
{"Les": [{"name": "site120 ","
Email ":" site120@163.com "," sex ":" male "},
{"Name": "site120_2", "email": "site1
20@163.com _ 2 "," sex ":" male _ 2 "}]} ')
- Puts cmdles ["cmdles"] [1] ["name"]
# Output site120_2
Rails has built-in AJAX support through RJS. There may not be many opportunities to use json. However, as a convenient data exchange format, pay attention to the value.