Thanks for all the fish
Thanks for all the fish

Reputation: 1701

Ruby: parsing string with backslash

string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"

How do I parse it? It keeps giving me error.

Upvotes: 0

Views: 1333

Answers (2)

chrmod
chrmod

Reputation: 1445

With ruby-2.0.0-p0:

string = "{:name=>\"2012 Honda Civic EX-L\", :price=>\"23100\", :dealer_name=>\"T AND T HOND\", :dealer_website=>\"http://autocatch.com/dealer/t-and-t-honda/index.htm\", :phone=>\"(888) 364-1858\", :ad=>\"1167269\", :stock=>\" 2120054N\", :year=>\"2012\", :make=>\"Honda\", :model=>\"Model Civic\", :trim=>\"EXL\", :mileage=>\"4629\", :body_style=>\"Coupe\", :transmission=>\"Automatic\", :ext_colour=>\"White\", :int_colour=>\"Grey\", :doors=>\"2Door\", :passengers=>\"Passengers \", :drive_train=>\"Front Wheel Drive\", :engine=>\"1.80\", :cylinders=>\"4Cylinder\", :fuel_type=>\"Type Gas\", :certified=>\"\", :e_tested=>\"\"}\n"
hash = eval(string)
hash[:name] # => "2012 Honda Civic EX-L"

What errors do you get exactly?

Upvotes: 1

user229044
user229044

Reputation: 239250

The backslashes are just escaping the quotation marks; they aren't actually in the string. As for parsing it, use eval and let Ruby parse it, if it's from a trusted source.

Upvotes: 1

Related Questions