How do I remove backslashes from a JSON string?

て烟熏妆下的殇ゞ 提交于 2019-12-21 09:15:08

问题


I have a JSON string that looks as below

'{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'

I need to change it to the one below using Ruby or Rails:

'{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"bar2"}]}}}'

I need to know how to remove those slashes.


回答1:


Use Ruby's String#delete! method. For example:

str = '{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'
str.delete! '\\'
puts str
#=> {"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}



回答2:


To avoid generating JSON with backslashes in console, use puts:

> hash = {test: 'test'}
=> {:test=>"test"}

> hash.to_json
 => "{\"test\":\"test\"}"

> puts hash.to_json
{"test":"test"}

You could also use JSON.pretty_generate, with puts of course.

> puts JSON.pretty_generate(hash)
{
  "test": "test"
}



回答3:


Replace all backslashes with empty string using gsub:

json.gsub('\\', '')

Note that the default output in a REPL uses inspect, which will double-quote the string and still include backslashes to escape the double-quotes. Use puts to see the string’s exact contents:

{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}

Further, note that this will remove all backslashes, and makes no regard for their context. You may wish to only remove backslashes preceding a double-quote, in which case you can do:

json.gsub('\"', '')



回答4:


I needed to print a pretty JSON array to a file. I created an array of JSON objects then needed to print to a file for the DBA to manipulate.

This is how i did it.

puts(((dirtyData.gsub(/\\"/, "\"")).gsub(/\["/, "\[")).gsub(/"\]/, "\]"))

It's a triple nested gsub that removes the \" first then removes the [" lastly removes the "]

I hope this helps




回答5:


I tried the earlier approaches and they did not seem to fix my issue. My json still had backslashes. However, I found a fix to solve this issue.

myuglycode.gsub!(/\"/, '\'')



来源:https://stackoverflow.com/questions/18325297/how-do-i-remove-backslashes-from-a-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!