Ruby parsing JSON
Ruby parsing Json example:
json = '["a", "B", "C"]' puts "Unsafe #{unsafe_json (json).inspect}" #Output Unsafe["a", "B", "C"]
Ruby parsing Json parses the above json string into Array. Such methods are not safe, for example:
json = 'puts "Danger Will Robinson"' puts "Unsafe #{unsafe_json (json).inspect}"
What should I output? Unfortunately, there is no parsing anything, and a warning pops up: warning: character class has `[' without escape safe method as follows:
module SafeJSON require 'monitor' def SafeJSON.build_safe_json ret = nil waiter = '' (MonitorMixin) wait_cond = waiter.new_cond do $SAFE = 4 ret = {|json| eval((/(["'])/s*:/s* (['"0-9tfn/[{])/){"#{$1}=>#{$2}"}) } do wait_cond.signal end end do wait_ cond.wait_while { ? } end return ret end @@parser = SafeJSON.build_safe_json # Safely parse the JSON input def (input) @@(input) rescue SecurityError return nil end end
Including this Module, you can use Ruby to parse Json:
peoples=(' {"peoples":[{"name":"site120"," email":"site120@","sex":"male"}, {"name":"site120_2","email":"site1 [email protected]_2","sex":"Male_2"}]}') puts peoples["peoples"][1]["name"] #Output site120_2
Ruby on Rails
Rails has built-in support for AJAX through RJS. Maybe there are not many opportunities to use json, but as a convenient format for data exchange, please pay attention to the value.
Here, use the Json plugin and install the command
gem install json_pure
Example of use:
require "open-uri" require 'json' def index uri = '*****' response = nil begin open(uri) do |http| response = end @json = JSON::parse(response) rescue => text #Exception handling ("GetMailListserror=" + text) [:error] = 'Failed to get the mailing list. ' end end
Here, the json parser requires the json format key that must be quoted. If there are no quotes, exceptions will be parsed.