Don't understand how to parse json - ruby-on-rails

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)

Related

JSON.parse appends , to string and then complains invalid token at ',

I'm parsing a webpage with nokogiri and then iterating through css selectors until I find the I'm looking for Then I run a regex to match the javascript portion only, and then try to parse it with JSON.parse but that returns error invalid token at ',{ ... If I run puts on the matched data it shows it without the prepended comma but the error occurs when I run JSON.parse JSON::ParserError: 822: unexpected token at ',{"skuAttr":"200007763:201336106;491:200004763#145cm","skuPropIds":"
file=File.open('product.html')
doc=Nokogiri::HTML.parse(file)
doc.css("script").each do |page|
if page.text=~/skuProducts/
skudata = page.text[/var skuProducts=\[(.+?)\];/, 1]
puts skudata
parsed = JSON.load(skudata)
end
end
If you're consistently seeing that comma prefixed and the rest of the JSON string looks valid... then why not just remove that leading comma and then try the JSON parse?

How to clear double quote marks in json?

I generated a json using NSJSONSerialization.This is my code:
// parameters is `Dictionary<String, AnyObject>?`
let json = try! NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions.init(rawValue: 0))
request.HTTPBody = json
But my server received this:
"{login:23232432434,mobile_captcha:,password:22e233434}"=>"[FILTERED]"
It seems server takes the whole json as a key and I think this because of that ".Maybe there is other reasons,please help me!
Those aren’t brackets; they’re (double) quotes/quotation marks. In valid JSON, quotation marks inside strings must be escaped with \, e.g. "Hello \"World\"".
The Web service you’re using is returning invalid JSON.
http://jsonlint.com is a useful resource to validate JSON strings.

How to parse values from a JSON field that is also a JSON?

I have a JSON that has one field that in itself contains another JSON. I am having trouble parsing values from this embedded JSON. I am using SwiftyJSON and can extract the embedded JSON as JSON type (swiftyJSON type). But I am unable to do anything with it further to get values from the embedded JSON.
thisjson[0]["MESSAGE_JSON_BODY"] will return a JSON type.
thisjson[0]["MESSAGE_JSON_BODY"].string will convert this JSON to string.
Now I need help parsing fields from MESSAGE_JSON_BODY JSON. How to parse the fields in the embedded JSON?
I figured out one way to solve this problem myself, here I print out the field value for "fieldkey":
if let stringdata: String = thisjson[0]["MESSAGE_JSON_BODY"].string{
var data: NSData = stringdata.dataUsingEncoding(NSUTF8StringEncoding)!
let msgjson = JSON(data: data)
println(msgjson["fieldkey"])
}

Rails: ActiveSupport JSON parse ill-formatted JSON

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

RoR: to_json on an array of hashes

I have an array of hashes in a Rails action which i return to client in json format:
{"msg": "Got report data.Check 'report' json object. ", "success": true, "reports": "[{\"total_transfers\": 0, \"total_keywords\": 0, \"keyword\": \"plum\", \"total_duration\":1464.0, \"total_calls\": 22, \"total_sms\": 0, \"avg_duration\": 67,\"total_email\": 0}]"}
In action i do: return reports.to_json but as you can see it does not look like valid json (why the escape characters?)
In client side js code, i do reports.length and get 163??? when it should say 1 because there is only one "report" in the reports array.
As you can see "reports" is one big string, instead of an array of a hash which you'd expect (163 is the length of the string, and this is why you can see escape characters). Which json library are you using with rails? What kind of object is your array of hash exactly? It might not have the to_json method implemented...
Alternatively you might try to convert your repsonse to yaml first, from that getting json is easier.
reports_array_object = eval("(" + reports + ")");
sweet!!!!

Resources