I'm trying to minify some inline JSON as part of my HTML minifier. How do I make this:
> {"@context": "http://schema.org", "@type": "WebSite"} <
Into this:
>{ "@context": "http://schema.org", "@type": "WebSite" }<
I've tried gsub[/\\", \\s+\\"/, ", "]
, gsub[/"\\"}"/, "\\" }"]
and gsub[/"\\"}"/, "\\" }"]
but that errors out.
syntax error, unexpected [, expecting ']' (SyntaxError)
[/"\"}"/, "\" }"]
^
syntax error, unexpected ',', expecting keyword_end
syntax error, unexpected ',', expecting keyword_end
syntax error, unexpected ']', expecting keyword_end
I've now also tried these but to no good:
[/>\s+{/, ">{ "] # > { => >{
[/}\s+>/, " }<"] # } < => }<
[%r/{"/, '{ %r/"'] # {" => { "
[%r/"}/, '%r/" }'] # "} => " }
[%r/",\s+/, ", "] # , " => , "
Resulting in:
syntax error, unexpected [, expecting ']' (SyntaxError)
[/}\s+>/, " }<"] # } < => }<
^
I would suggest a different approach:
require JSON
str = '{"@context": "http://schema.org", "@type": "WebSite"}'
new_str = JSON.parse(str).to_json
puts new_str
> {"@context":"http://schema.org","@type":"WebSite"}
Use a %r Regexp literal to escape all characters but one :
a = '{"@context": "http://schema.org", "@type": "WebSite"}'
a.gsub(%r/{"/, '{ "').gsub(%r/"}/, '" }').gsub(/\s+/, ' ')
#=> { "@context": "http://schema.org", "@type": "WebSite" }
using %r{ ... }
escapes all characters but {
and }
,same goes for /
, (
, etc ...
credit : Escaping '“' with regular double quotes using Ruby regex
It will escapes double quotes
gsub(/("|")/, 34.chr)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.