diff --git a/README b/README index cf5291e..2b6828e 100644 --- a/README +++ b/README @@ -24,11 +24,11 @@ grokking the structure of output). This can also be overridden to output formatted XML or JSON. Execute httparty --help for all the options. Below is an example of how easy it is. - httparty "http://twitter.com/statuses/public_timeline.json" -f json + httparty "http://twitter.com/statuses/public_timeline.json" == REQUIREMENTS: -* JSON ~> 1.1 +* You like to party! == INSTALL: diff --git a/Rakefile b/Rakefile index 4fd399d..bcac702 100644 --- a/Rakefile +++ b/Rakefile @@ -14,7 +14,6 @@ Echoe.new(ProjectName, HTTParty::Version) do |p| p.url = "http://#{ProjectName}.rubyforge.org" p.author = "John Nunemaker" p.email = "nunemaker@gmail.com" - p.extra_deps = [['json', '~> 1.1']] p.need_tar_gz = false p.docs_host = WebsitePath end diff --git a/bin/httparty b/bin/httparty index 2dbea74..729cc8a 100755 --- a/bin/httparty +++ b/bin/httparty @@ -82,7 +82,13 @@ else puts "Status: #{response.code}" case opts[:output_format] when :json - puts JSON.pretty_generate(response) + begin + require 'rubygems' + require 'json' + puts JSON.pretty_generate(response.delegate) + rescue LoadError + puts YAML.dump(response.delegate) + end when :xml REXML::Document.new(response.body).write(STDOUT, 2) puts diff --git a/lib/httparty.rb b/lib/httparty.rb index 1a35007..0c4dbad 100644 --- a/lib/httparty.rb +++ b/lib/httparty.rb @@ -2,10 +2,6 @@ $:.unshift(File.dirname(__FILE__)) require 'net/http' require 'net/https' -require 'rubygems' -gem 'json', '>= 1.1.3' -require 'json' - require 'module_level_inheritable_attributes' require 'core_extensions' @@ -136,4 +132,5 @@ end require 'httparty/exceptions' require 'httparty/request' require 'httparty/response' +require 'httparty/json' require 'httparty/cookie_hash' diff --git a/lib/httparty/json.rb b/lib/httparty/json.rb new file mode 100644 index 0000000..17bbd62 --- /dev/null +++ b/lib/httparty/json.rb @@ -0,0 +1,64 @@ +# Copyright (c) 2004-2008 David Heinemeier Hansson +# 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 'yaml' +require 'strscan' + +module HTTParty + module JSON #:nodoc: + class ParseError < StandardError; end + + def self.decode(json) + YAML.load(convert_json_to_yaml(json)) + rescue ArgumentError => e + raise ParseError, "Invalid JSON string" + end + + protected + # matches YAML-formatted dates + DATE_REGEX = /^\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \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: + scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, [] + while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/) + case char = scanner[1] + when '"', "'" + if !quoting + quoting = char + pos = scanner.pos + elsif quoting == char + 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 + end + quoting = false + end + when ":","," + marks << scanner.pos - 1 unless quoting + end + end + + if marks.empty? + json.gsub(/\\\//, '/') + else + left_pos = [-1].push(*marks) + right_pos = marks << json.length + output = [] + left_pos.each_with_index do |left, i| + output << json[left.succ..right_pos[i]] + end + output = output * " " + + times.each { |i| output[i-1] = ' ' } + output.gsub!(/\\\//, '/') + output + end + end + end +end \ No newline at end of file diff --git a/lib/httparty/request.rb b/lib/httparty/request.rb index 4d79d32..ca3bf7a 100644 --- a/lib/httparty/request.rb +++ b/lib/httparty/request.rb @@ -103,7 +103,7 @@ module HTTParty when :xml ToHashParser.from_xml(body) when :json - JSON.parse(body) + HTTParty::JSON.decode(body) else body end diff --git a/lib/httparty/response.rb b/lib/httparty/response.rb index d98d8ef..9d8f7e2 100644 --- a/lib/httparty/response.rb +++ b/lib/httparty/response.rb @@ -1,6 +1,7 @@ module HTTParty class Response < BlankSlate #:nodoc: attr_accessor :body, :code, :headers + attr_reader :delegate def initialize(delegate, body, code, headers) @delegate = delegate diff --git a/spec/as_buggery_spec.rb b/spec/as_buggery_spec.rb index 832f483..2a037ca 100644 --- a/spec/as_buggery_spec.rb +++ b/spec/as_buggery_spec.rb @@ -1,5 +1,4 @@ require File.join(File.dirname(__FILE__), 'spec_helper') - require 'activesupport' describe Hash do diff --git a/spec/httparty/json_spec.rb b/spec/httparty/json_spec.rb new file mode 100644 index 0000000..ed7da21 --- /dev/null +++ b/spec/httparty/json_spec.rb @@ -0,0 +1,41 @@ +require File.join(File.dirname(__FILE__), '..', 'spec_helper') + +describe HTTParty::JSON do + TESTS = { + %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, + %q({returnTo:{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}}, + %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}}, + %q({"returnTo":{"\/categories":1}}) => {"returnTo" => {"/categories" => 1}}, + %({"returnTo":[1,"a"]}) => {"returnTo" => [1, "a"]}, + %({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]}, + %({a: "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"}, + %({a: "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"}, + %({a: "2007-01-01"}) => {'a' => Date.new(2007, 1, 1)}, + %({a: "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)}, + # no time zone + %({a: "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"}, + %([]) => [], + %({}) => {}, + %(1) => 1, + %("") => "", + %("\\"") => "\"", + %(null) => nil, + %(true) => true, + %(false) => false, + %q("http:\/\/test.host\/posts\/1") => "http://test.host/posts/1" + } + + TESTS.each do |json, expected| + it "should decode json (#{json})" do + lambda { + HTTParty::JSON.decode(json).should == expected + }.should_not raise_error + end + end + + it "should raise error for failed decoding" do + lambda { + HTTParty::JSON.decode(%({: 1})) + }.should raise_error(HTTParty::JSON::ParseError) + end +end \ No newline at end of file