I have few lines of code in a file (code has few new lines, tabs, string and pattern-string)
I want to get this content of file as a string value, so that it can be sent as a string value of some parameter in json {param1: "value1", code: "code-content-from-file-should-go-here"}
lets say file content is
function string.urlDecode(str)
if string.isEmpty(str) then return str end
str = string.gsub(str, "+", " ")
str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
str = string.gsub(str, "\r\n", "\n")
return str
end
which should get converted to (what I see here is newline, tabs, in general code formatting is preserved, " \ etc are escaped)
function string.urlDecode(str)\n if string.isEmpty(str) then return str end\n str = string.gsub(str, \"+\", \" \")\n str = string.gsub(str, \"%%(%x%x)\", function(h) return string.char(tonumber(h, 16)) end)\n str = string.gsub(str, \"\\r\\n\", \"\\n\")\n return str\nend
So that json becomes
{param1: "value1", code: "function string.urlDecode(str)\n if string.isEmpty(str) then return str end\n str = string.gsub(str, \"+\", \" \")\n str = string.gsub(str, \"%%(%x%x)\", function(h) return string.char(tonumber(h, 16)) end)\n str = string.gsub(str, \"\\r\\n\", \"\\n\")\n return str\nend"}
While conversion of file-content to string in above mentioned manner can be done using sed (got from few related slackoverflow threads like How can I replace a newline (\n) using sed?), but I will have to handle each scenario like newline, tabs, ", \, and if there are any other special characters that needs to be escaped (which I dont know)
Is there any bash command (or maybe python module) that can handle all such scenario's for code-content-from-file to string conversion?
As this sees like a common use case if someone wants to send code content in JSON