Rails: ActiveSupport JSON parse ill-formatted JSON - ruby-on-rails

The response I get is
page_play_model_exponentModel__getNum({"code":1,"message":"","result":{"icode":"JXdywDcV0hA","totalVv":6}})
This is not a typical JSON response. So when I use activesupport like
decode_response = ActiveSupport::JSON.decode(response), it will report
JSON::ParserError: 795: unexpected token at 'page_play_model_exponentModel__getN
um({"code":1,"message":"","result":{"icode":"JXdywDcV0hA","totalVv":6}})
'
How can I parse this properly? I want the totalVv value and I can get it ugly,
like
totalVv = response.split("'totalVv':")[1].split("}")[0], but this is just weird.

It looks like a JSONP response, but you could use a regex to extract the JSON
response = 'page_play_model_exponentModel__getNum({"code":1,"message":"","result":{"icode":"JXdywDcV0hA","totalVv":6}})'
json = /(\{.*\})/.match().to_s

Related

Rails - Feedjira No valid parser for XML

I used Feedjira gem in rails. I want to get some data from URL but I got an error like this:
Feedjira::NoParserAvailable No valid parser for XML.
My code:
url = "https://tickets.companyname.com/activity.atom?key=#{api_key}&user_id=#{user_id}"
feed = Feedjira::Feed.fetch_and_parse url // this line i'm getting the error

Don't understand how to parse json

data = {
"CEO": "William Hummel",
"CFO": "Carla Work"
}
I'm trying to parse the json data above with JSON.parse(data) in IRC, but it won't work.
I'm getting the following error: "SyntaxError: (irb):44: syntax error, unexpected ':', expecting tASSOC"
JSON.parse takes a string argument. You are trying to construct a Hash using JSON syntax. Use a string instead:
data = '{"CEO": "William Hummel", "CFO": "Carla Work"}'
JSON.parse(data)

how deserialize a json in rails

I send a http request and get a json for response like below:
{"total":"1200.0","used":"35.0","available":1165.0}
now I want deserialize this json and show to user in a table like below:
total : 1200
used : 35
availabele : 1165
I use JSON.parse(response),but I get below error:
no implicit conversion of Net::HTTPOK into String
How can I do this?
Net::HTTP has responses in body. so, Try
JSON.parse response.body
You have to pass the response.body as the parameters into the JSON.parse method then assign the method to a variable to use elsewhere in your code.
parse_res = JSON.parse(res.body)

Rails: How to send a http get request with UTF-8 encoding

I'm trying to use an external API to get some information
address=self.address
response = HTTParty.get("http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a")
decode_response = ActiveSupport::JSON.decode(response)
However, the address is in chinese, so I need to convert into UTF-8 code,
if not I'll get URI::InvalidURIError (bad URI(is not URI?): How to do it?
I tried address=self.address.force_encoding('utf-8'), but it does not work, maybe I should use other method instead?
UPDATE:
uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
encoded_uri = URI::encode(uri)
response = HTTParty.get(encoded_uri)
decode_response = ActiveSupport::JSON.decode(response)
self.latitude = decode_response['result']['location']['lat']
and I get can't convert HTTParty::Response into String. What's wrong with it?
I found something here, I think I'll need to tell Httparty explicityly to parse it with JSON?
You could save this to a file 'geo.rb' and run ruby geo.rb
require 'uri'
require 'httparty'
address = "中国上海"
uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
encoded_uri = URI::encode uri
puts HTTParty.get(encoded_uri)

743: unexpected token at '... in Ruby on Rails

I saved a file named array.json on my Dropbox folder and i access to it via Dropbox API. All works fine, but when i retrieve JSON content i cannot JSON.parse that string!!
session = DropboxSession.new(APP_KEY, APP_SECRET)
session.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
client = DropboxClient.new(session, ACCESS_TYPE)
json = client.get_file(DIRECTORY + '/array.json')
#json = JSON.parse json
Error:
743: unexpected token at '{"Nome" : "Mario Rossi",
"C.F." : "ABCDEFGHILMNOP",
"Booking Assistance" : "MARIO",
"Status of reservation" : "25/11/2011"}'
JSON string is valid!! if i copy this string and paste it (manually) as parameter in JSON.parse(), json is parsed correctly!! So i think is a encoding problem...but where i wrong?
We have abandoned the json parsing backend that is the default in Rails. The default backend is YAML based and imo a useless mess. After several gotchas parsing unicode, and dates in some cases, we discovered that the backend can be replaced via configuration.
You can substitute the parsing backend in an initializer
ActiveSupport::JSON.backend = "JSONGem"
There are several gems that can be used as the backend, we just use the json gem
gem 'json'

Resources