Browse Source

added a new function to escape properly json, fixes #3282

Juan Linietsky 9 years ago
parent
commit
4fdab4f555
4 changed files with 23 additions and 1 deletions
  1. 1 1
      core/io/json.cpp
  2. 15 0
      core/ustring.cpp
  3. 1 0
      core/ustring.h
  4. 6 0
      core/variant_call.cpp

+ 1 - 1
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()+"\"";
 
 	}
 

+ 15 - 0
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;

+ 1 - 0
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;

+ 6 - 0
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());