Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

JSON gem no longer dependency. Stole json decoding from ActiveSupport…

… and bundled just that with HTTParty.
  • Loading branch information...
commit e5e3d54bbc213b94efe41e30ecd146eb254c61ee 1 parent 0112a89
John Nunemaker authored
4 README
View
@@ -24,11 +24,11 @@ grokking the structure of output). This can also be overridden to output
formatted XML or JSON. Execute <tt>httparty --help</tt> 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:
1  Rakefile
View
@@ -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
8 bin/httparty
View
@@ -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
5 lib/httparty.rb
View
@@ -2,10 +2,6 @@
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 @@ def self.delete(*args)
require 'httparty/exceptions'
require 'httparty/request'
require 'httparty/response'
+require 'httparty/json'
require 'httparty/cookie_hash'
64 lib/httparty/json.rb
View
@@ -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
2  lib/httparty/request.rb
View
@@ -103,7 +103,7 @@ def parse_response(body)
when :xml
ToHashParser.from_xml(body)
when :json
- JSON.parse(body)
+ HTTParty::JSON.decode(body)
else
body
end
1  lib/httparty/response.rb
View
@@ -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
1  spec/as_buggery_spec.rb
View
@@ -1,5 +1,4 @@
require File.join(File.dirname(__FILE__), 'spec_helper')
-
require 'activesupport'
describe Hash do
41 spec/httparty/json_spec.rb
View
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.