Bug 1467759 - Escape all the property names in JSONWriter. r?froydnj
Scalar property names (e.g. IntProperty) are already escaped correctly.
This patch escapes the collection property names (e.g. StartObjectProperty)
as well (and adds test coverage for it).
MozReview-Commit-ID: 68kkjPb2ZN7
--- a/mfbt/JSONWriter.h
+++ b/mfbt/JSONWriter.h
@@ -308,19 +308,17 @@ protected:
mNeedNewlines[mDepth] = true;
}
void StartCollection(const char* aMaybePropertyName, const char* aStartChar,
CollectionStyle aStyle = MultiLineStyle)
{
Separator();
if (aMaybePropertyName) {
- mWriter->Write("\"");
- mWriter->Write(aMaybePropertyName);
- mWriter->Write("\": ");
+ PropertyNameAndColon(aMaybePropertyName);
}
mWriter->Write(aStartChar);
mNeedComma[mDepth] = true;
mDepth++;
NewVectorEntries();
mNeedNewlines[mDepth] =
mNeedNewlines[mDepth - 1] && aStyle == MultiLineStyle;
}
--- a/mfbt/tests/TestJSONWriter.cpp
+++ b/mfbt/tests/TestJSONWriter.cpp
@@ -522,18 +522,60 @@ void TestDeepNesting()
w.EndArray();
}
}
w.End();
Check(w.WriteFunc(), expected);
}
+void TestEscapedPropertyNames()
+{
+ const char* expected = "\
+{\"i\\t\": 1, \"array\\t\": [null, [{}], {\"o\\t\": {}}, \"s\"], \"d\\t\": 3.33}\n\
+";
+
+ JSONWriter w(MakeUnique<StringWriteFunc>());
+
+ w.Start(w.SingleLineStyle);
+
+ w.IntProperty("i\t", 1);
+
+ w.StartArrayProperty("array\t");
+ {
+ w.NullElement();
+
+ w.StartArrayElement(w.MultiLineStyle); // style overridden from above
+ {
+ w.StartObjectElement();
+ w.EndObject();
+ }
+ w.EndArray();
+
+ w.StartObjectElement();
+ {
+ w.StartObjectProperty("o\t");
+ w.EndObject();
+ }
+ w.EndObject();
+
+ w.StringElement("s");
+ }
+ w.EndArray();
+
+ w.DoubleProperty("d\t", 3.33);
+
+ w.End();
+
+ Check(w.WriteFunc(), expected);
+}
+
int main(void)
{
TestBasicProperties();
TestBasicElements();
TestOneLineObject();
TestStringEscaping();
TestDeepNesting();
+ TestEscapedPropertyNames();
return 0;
}