Rails controller render json without encoding - json

I am trying to send json data from my rails controller but it always converts & into unicode \u0026. Is it possible to tell rails controller not to convert & into unicode \u0026 ?
Below is how my method looks like in controller (this is just dummy test method)
def send_detail
render json: { data: "name?surname&otherdetail" }
end
when I visit localhost:3000/tests/send_detail in postman, I get { "data":"name?surname\u0026otherdetail" }
How can I tell render method not to convert & into unicode character \u0026 ?. If possible I would like to preserve & only for this method rather than changing Rails config to not covert json data in unicode character for all rails application.
UPDATE
I am able to force rails not to covert & into unicode character by adding this line ActiveSupport.escape_html_entities_in_json = false but this changes the settings in all Rails application, which is not what I want. I only like to preserve & in one method.

You can manually convert it in the single action that you want it not to apply:
def send_detail
render json: JSON.generate({ data: "name?surname&otherdetail" })
end

Related

Invalid JSON syntax error in configuration file on homebridge

{
"bridge":{
"name":"Homebridge F8F5",
"username":"0E:8F:12:8D:F8:F5",
"port":51739,
"pin":"670-48-238"
},
"accessories":[
],
"platforms":[
{
"name":"Config",
"port":8581,
"platform":"config"
}
]
}{
"accessories":[
{
"name":"Roku",
"accessory":"Roku",
"ip":"http://10.204.1.238:8060",
}
I am getting an error when I try to run this config file in homebridge. What am I doing wrong? When I try to submit it through the web interface it will not allow me to and says “Config JSON error: invalid json syntax” Any help will be welcome! I have tried to put it through an online json error finder and it narrowed it down to this snippet.
Ummm... looks like you tried to edit this file without knowing the basic concepts of JSON.
Start by reading JSON - Introduction on W2Schools.com
Also, if you're not sure, use an online JSON validator. Use your fav. search engine to look for "JSON cleaner". (I use JSON Formatter & Validator at Curious Concept.)
Off the bat I can see a few issues with the JSON you provided.
the "}{" string ... what's that for? JSON cannot parse that ... either add "," between (if you wanted a new set) or (in this case) remove it.
you have two "accessories". JSON usually get parsed into an object or array ... one cannot have duplicates on the ket names. (In this case) remove the first one.
the second "accessories" array (denoted by "[") has no end (no "]")
the whole set (started with "{") has no end (no "}")

Parse JSON in to Strings with escape characters for GWT Test Case

I've come up with a doubt around JSON files.
So, we're building a test case for a GWT application. The data it feeds from is in JSON files generated from a SQL database.
When testing the methods that work with data, we do it from sources held in String files, so to keep integrity with the original data, we just clone the original JSON values in to a String with escape sequences.
The result of this being that if a JSON entry shows like this:
{"country":"India","study_no":87}
The parsed result will come up like this in order for our tools to recognise them:
"[" + "{\"country\":\"India\",\"study_no\":87}" + "]"
The way we do it now is taking each JSON object and putting it between "" in IntelliJ, which automatically parses all double quotes in to escape sequences. This is ok if we only wanted a few objects, but What if we wanted a whole dataset?
So my question is, does anyone know or has created an opensource script to automate this tedious task?
One thing you could do is to wrap window.escape() using JsInterop or JSNI. For example:
#JsType(isNative="true", name="window")
public class window {
public native String escape(String toBeEscape);
}
and then apply to your results.

JSON::GeneratorError arising with the use of to_json method

I am getting the
JSON::GeneratorError: source sequence is illegal/malformed utf-8
when I am using to_json method. I have not overridden the to_json method anywhere.
I have referred this question and also this one
But as Ruby 1.8 does not have the concept of string encodings the solution is not helping me.
How can I solve this issue without the requirement to escape the specific non-ascii characters?
I am on ruby 1.8.7
The only Rails solution I am aware of would be:
# [AM] Monkeypatch to support multibyte utf-8
module ::ActiveSupport::JSON::Encoding
def self.escape(string)
if string.respond_to?(:force_encoding)
string = string.encode(
::Encoding::UTF_8,
:undef => :replace
).force_encoding(::Encoding::BINARY)
end
json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
json = %("#{json}")
json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
json
end
end
I believe there could be the same patch applied directly to JSON::GeneratorError.

Auto-encoding Catalyst::View::JSON

I use DBIx class for selecting data from database;
I send response from controller to client using serialization to json using Catalyst::View::JSON
But utf8-data selected from database needs to be decoded to perl-string from utf-8 before sending to client like this
use Encode;
...
sub get_fruits :Path('getfruits') :Args(0) {
my $fruits = [$c->model('DB::Fruit')->search({})->hashref_array];
# Hated encode data loop
foreach (#$fruits) {
$_->{name} = decode('utf8', $_->{name});
}
$c->stash({fruits => $fruits});
$c->forward('View::JSON');
}
Is it possible to decode data automatically in the View?
The Catalyst model always has to ensure that the data is decoded, regardless of where it is used. The view has to ensure the data is encoded correctly.
You have to make sure that your model decodes data coming from the database. If you are using DBIx::Class read Using Unicode.
This may be as simple as ensuring that Catalyst::View::JSON is using a JSON encoder that supports UTF8 encoding. I believe that if you use JSON::XS with Catalyst::View::JSON it will perform UTF8 encoding by default. You can make sure that Catalyst::View::JSON is using JSON::XS using the json_driver config variable.
Alternatively you can override JSON encoding in Catalyst::View::JSON as detailed in the docs

Write json object with controller using rendered jsp

I use Spring MVC.
I want to render some jsp by forwarding to it. And then I want to write the result to json.
For exmple I want to render my complex jsp and on exit I want to get:
{"result":"ok","html":"......."}
How can I do this?
I've tried to look at
request.getRequestDispatcher("tutorMini").forward(request, response)
But if I can't pass response to it, bcz it should write all output to it.
And I've tried to use some json tags in jsp, but it has some troubles with hierarchy:
HTML output with jsp:include and json-taglib
Since you need to apply additional conversion when inserting HTML into JSON (escape ' and "), you cannot write output of your JSP to the response directly.
So, you need to create an instance of ServletResponseWrapper that would save the output (by overriding getWriter() and/or getOutputStream()) and pass it to RequestDispatcher.include() (it looks more appropriate than forward() for this case):
MyServletResponseWrapper wrapper = new MyServletResponseWrapper(response);
request.getRequestDispatcher("tutorMini").include(request, wrapper);
String html = wrapper.getSavedOutput();
Then you can insert the saved content into JSON, escaping it appropriately.