Reputation: 15259
I am using Ruby on Rails 3 and I would like, in some way, to convert a string to_json
and to_xml
.
Just to know, I need to return that string in a Rack method in this way:
[404, {"Content-type" => "application/json"}, ["Bad request"]]
# or
[404, {"Content-type" => "application/xml"}, ["Bad request"]]
However what I need is only to convert that string to_json
and to_xml
? How is it possible do that?
Upvotes: 2
Views: 17890
Reputation: 27497
In your controller, just pass in the XML string:
render xml: "<myxml><cool>fff</cool></myxml>"
Upvotes: 2
Reputation: 1612
Sometimes you must add a require 'json'
in your file (after installing the gem, JSON implementation for Ruby ) and do:
JSON.parse("Bad request").to_json
or you could try:
ActiveSupport::JSON.encode("Bad request").to_json
But in your case maybe the best approach is respond correctly:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @somearray }
format.json { render :json => @somearray }
end
Alternatively you could do:
mystring_json = '{"bar":"foo"}'
[404, {'Content-Type' => 'application/json'}, [mysrting_json]] #json stuff
mystring_xml = '<?xml><bar>foo</bar>'
[404, {'Content-Type' => 'application/xml'}, [mysrting_xml]] #xml stuff
Upvotes: 5
Reputation: 6515
JSON follows JavaScript syntax, so a string in JSON is easy:
[404, {"Content-type" => "application/json"}, ["'Bad request'"]]
As for XML, the answer is not so simple. You'd have to decide what tag structure you want to use and go from there. Remember that an XML doc has, at a minimum, a root tag. So, you could return an XML doc like this:
<?xml version="1.0" encoding="utf-8"?>
<response>Bad request</response>
One way to do this would be to use the Builder gem:
However, I'm not entirely certain why you would need to return a string all by itself as JSON or XML. JSON and XML are typically used for transmitting structured data, e.g. arrays, nested data, key-value pairs, etc.. Whatever your client is, it could presumably just interpret the string as-is, without any JSON or XML ecoding, no?
Upvotes: 1