lib/crack/json.rb in crack-0.4.0 vs lib/crack/json.rb in crack-0.4.1

- old
+ new

@@ -36,16 +36,16 @@ str.force_encoding('UTF-8') if defined?(Encoding) && str.respond_to?(:force_encoding) str.gsub(/\\u0000/, "").gsub(/\\[u|U]([0-9a-fA-F]{4})/) { [$1.hex].pack("U") } end # matches YAML-formatted dates - DATE_REGEX = /^\d{4}-\d{2}-\d{2}$|^\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?$/ + DATE_REGEX = /^\d{4}-\d{2}-\d{2}$|^\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)$/ # Ensure that ":" and "," are always followed by a space def self.convert_json_to_yaml(json) #:nodoc: json = String.new(json) #can't modify a frozen string - scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, [] + scanner, quoting, marks, pos, date_starts, date_ends = StringScanner.new(json), false, [], nil, [], [] while scanner.scan_until(/(\\['"]|['":,\/\\]|\\.)/) case char = scanner[1] when '"', "'" if !quoting quoting = char @@ -54,11 +54,12 @@ if json[pos..scanner.pos-2] =~ DATE_REGEX # found a date, track the exact positions of the quotes so we can remove them later. # oh, and increment them for each current mark, each one is an extra padded space that bumps # the position in the final YAML output total_marks = marks.size - times << pos+total_marks << scanner.pos+total_marks + date_starts << pos+total_marks + date_ends << scanner.pos+total_marks end quoting = false end when "/" if !quoting @@ -82,12 +83,20 @@ left_pos.each_with_index do |left, i| output << json[left.succ..right_pos[i]] end output = output * " " - times.each { |i| output[i-1] = ' ' } + format_dates(output, date_starts, date_ends) output.gsub!(/\\\//, '/') output + end + end + + def self.format_dates(output, date_starts, date_ends) + if YAML.constants.include?('Syck') + (date_starts + date_ends).each { |i| output[i-1] = ' ' } + else + date_starts.each { |i| output[i-2] = '!!timestamp ' } end end end end