tamouse - thank you very much for taking the time to answer my question.
it looks even simpler and cleaner in ruby !
we needed the jScript command "JSON.parse" because of quotes being
passed and other characters inside the json-string that might interfere
with the string loading properly.
But in this case, the JSON object data is right in the code, no need to quote it, then parse it client side if you just write it directly into the source you’re sending.
Here’s a tiny example, based on sinatra:
get '/testjson' do ||
erb :testjson, locals: {this_hash: {a: [1,2,3], "BBB" => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "classic" => ["a fine thing", "I do now", "blueberry", :pudding, 3.1415]}}
end
Then the erb view testjson.erb contains:
<h1>Testing sending JSON directly</h1>
<script>
const Foo = <%= this_hash.to_json %>;
console.log(Foo);
</script>
and this is the source html in the browser:
<h1>Testing sending JSON directly</h1>
<script>
const Foo = {"a":[1,2,3],"BBB":"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","classic":["a fine thing","I do now","blueberry","pudding",3.1415]};
console.log(Foo);
</script>
So, no extra quoting, parsing, etc.
i am thinking something like this might work:
const Foo = JSON.parse("<%= big_extraction_of_data.to_json %>");
side-note: i find it extremely useful to create a monster structure and
just pass it down to jScript as is, and let jScript (or jQuery) do all
the work. i have been able to collapse the size of pages this way quite
dramatically, assuming my user will probably never need to see all the
data at the same time.
Putting it in a string, then parsing it just seems like extra work. Just insert the JSON object in directly, and assign it.
i have my users click on a link, then the html is auto-generated via
jQuery and that code is used in a pop-up window. the overall page size
is probably only 10% of what it takes when all the html is generated
from the server.
It’s certainly valid for a lot of interactions.
···
On Nov 12, 2013, at 7:03 PM, mark edwards <lists@ruby-forum.com> wrote:
--
Posted via http://www.ruby-forum.com/\.