From 4fdab4f555f3f7e1d3b070244d88ce18c3282a15 Mon Sep 17 00:00:00 2001 From: Juan Linietsky Date: Sun, 10 Jan 2016 15:01:06 -0300 Subject: [PATCH] added a new function to escape properly json, fixes #3282 --- core/io/json.cpp | 2 +- core/ustring.cpp | 15 +++++++++++++++ core/ustring.h | 1 + core/variant_call.cpp | 6 ++++++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/core/io/json.cpp b/core/io/json.cpp index 45a97ed7200..f9a8638d06b 100644 --- a/core/io/json.cpp +++ b/core/io/json.cpp @@ -86,7 +86,7 @@ String JSON::_print_var(const Variant& p_var) { s+="}"; return s; }; - default: return "\""+String(p_var).c_escape()+"\""; + default: return "\""+String(p_var).json_escape()+"\""; } diff --git a/core/ustring.cpp b/core/ustring.cpp index 21c0d78fdba..ee750c39e52 100644 --- a/core/ustring.cpp +++ b/core/ustring.cpp @@ -3158,6 +3158,21 @@ String String::c_escape() const { return escaped; } +String String::json_escape() const { + + String escaped=*this; + escaped=escaped.replace("\\","\\\\"); + escaped=escaped.replace("\b","\\b"); + escaped=escaped.replace("\f","\\f"); + escaped=escaped.replace("\n","\\n"); + escaped=escaped.replace("\r","\\r"); + escaped=escaped.replace("\t","\\t"); + escaped=escaped.replace("\v","\\v"); + escaped=escaped.replace("\"","\\\""); + + return escaped; +} + String String::xml_escape(bool p_escape_quotes) const { String str=*this; diff --git a/core/ustring.h b/core/ustring.h index 2b967d368a0..9276afa0f7b 100644 --- a/core/ustring.h +++ b/core/ustring.h @@ -211,6 +211,7 @@ public: String http_unescape() const; String c_escape() const; String c_unescape() const; + String json_escape() const; String world_wrap(int p_chars_per_line) const; String percent_encode() const; diff --git a/core/variant_call.cpp b/core/variant_call.cpp index 2122640be89..90f868c8663 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -272,6 +272,9 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var VCALL_LOCALMEM0R(String,get_file); VCALL_LOCALMEM0R(String,xml_escape); VCALL_LOCALMEM0R(String,xml_unescape); + VCALL_LOCALMEM0R(String,c_escape); + VCALL_LOCALMEM0R(String,c_unescape); + VCALL_LOCALMEM0R(String,json_escape); VCALL_LOCALMEM0R(String,percent_encode); VCALL_LOCALMEM0R(String,percent_decode); VCALL_LOCALMEM0R(String,is_valid_identifier); @@ -1286,6 +1289,9 @@ _VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_SCS(#m_method),VCALL(m_cl ADDFUNC0(STRING,STRING,String,get_file,varray()); ADDFUNC0(STRING,STRING,String,xml_escape,varray()); ADDFUNC0(STRING,STRING,String,xml_unescape,varray()); + ADDFUNC0(STRING,STRING,String,c_escape,varray()); + ADDFUNC0(STRING,STRING,String,c_unescape,varray()); + ADDFUNC0(STRING,STRING,String,json_escape,varray()); ADDFUNC0(STRING,STRING,String,percent_encode,varray()); ADDFUNC0(STRING,STRING,String,percent_decode,varray()); ADDFUNC0(STRING,BOOL,String,is_valid_identifier,varray());