Skip to content

Commit 5c41df3

Browse files
committed
[picojson] Let objects be ordered when serializing
This PR changes the serialization logic of objects to follow the insertion order of elements to keep the output consistent across different platforms.
1 parent f498cef commit 5c41df3

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

3rdparty/picojson/picojson.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,24 @@ void value::_serialize(Iter oi, int indent) const {
727727
if (indent != -1) {
728728
++indent;
729729
}
730+
731+
#if PICOJSON_USE_ORDERED_OBJECT
732+
for (auto i = u_.object_->ordered_keys().begin();
733+
i != u_.object_->ordered_keys().end(); ++i) {
734+
if (i != u_.object_->ordered_keys().begin()) {
735+
*oi++ = ',';
736+
}
737+
if (indent != -1) {
738+
_indent(oi, indent);
739+
}
740+
serialize_str(*i, oi);
741+
*oi++ = ':';
742+
if (indent != -1) {
743+
*oi++ = ' ';
744+
}
745+
u_.object_->at(*i)._serialize(oi, indent);
746+
}
747+
#else
730748
for (object::const_iterator i = u_.object_->begin(); i != u_.object_->end(); ++i) {
731749
if (i != u_.object_->begin()) {
732750
*oi++ = ',';
@@ -741,6 +759,7 @@ void value::_serialize(Iter oi, int indent) const {
741759
}
742760
i->second._serialize(oi, indent);
743761
}
762+
#endif
744763
if (indent != -1) {
745764
--indent;
746765
if (!u_.object_->empty()) {

3rdparty/picojson/test_picojson.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,21 @@ void test_modifier() {
5858
assert((obj.ordered_keys() == std::vector<std::string>{}));
5959
}
6060

61+
void test_serializer() {
62+
picojson::object obj;
63+
64+
obj["bar"] = picojson::value(static_cast<int64_t>(10));
65+
obj["baz"] = picojson::value(10.5);
66+
obj["foo"] = picojson::value(true);
67+
68+
picojson::value v(obj);
69+
70+
assert((v.serialize(false) == "{\"bar\":10,\"baz\":10.5,\"foo\":true}"));
71+
}
72+
6173
int main() {
6274
test_constructor();
6375
test_modifier();
76+
test_serializer();
6477
return 0;
6578
}

0 commit comments

Comments
 (0)