Skip to content

Commit 93a68fc

Browse files
authored
Merge pull request #46 from steinwurf/improve-unicode-escape-sequence-support
improve unicode escape sequence support
2 parents 08632e1 + 521fc44 commit 93a68fc

4 files changed

Lines changed: 46 additions & 3 deletions

File tree

NEWS.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ every change, see the Git log.
66

77
Latest
88
------
9-
* tbd
9+
* Patch: Better support for unicode escape sequences.
1010

1111
10.0.0
1212
------

src/bourne/json.cpp

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,16 +324,26 @@ std::string json::to_string() const
324324
assert(is_string());
325325
const std::string& str = *m_internal.m_string;
326326
std::string output;
327-
for (std::size_t i = 0; i < str.length(); ++i)
327+
auto size = str.length();
328+
for (std::size_t i = 0; i < size; ++i)
328329
{
329330
switch (str[i])
330331
{
331332
case '\"':
332333
output += "\\\"";
333334
break;
334335
case '\\':
335-
output += "\\";
336+
{
337+
// Check if the next character is a unicode escape sequence
338+
if (i + 1 < size && str[i + 1] == 'u')
339+
{
340+
output += "\\u";
341+
i += 1;
342+
break;
343+
}
344+
output += "\\\\";
336345
break;
346+
}
337347
case '\b':
338348
output += "\\b";
339349
break;

test/src/test_json.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,3 +287,18 @@ TEST(test_json, test_keys)
287287
}
288288
EXPECT_EQ(4U, obj.keys().size());
289289
}
290+
291+
TEST(test_json, test_unicode_dump)
292+
{
293+
{
294+
bourne::json object({"unicode", "\u00E6"});
295+
std::string expected = "{\"unicode\":\"\u00E6\"}";
296+
EXPECT_EQ(expected, object.dump_min());
297+
}
298+
299+
{
300+
bourne::json object({"bad_unicode", "\\u0"});
301+
std::string expected = "{\"bad_unicode\":\"\\u0\"}";
302+
EXPECT_EQ(expected, object.dump_min());
303+
}
304+
}

test/src/test_parser.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,21 @@ TEST(test_parser, test_exception_throw)
194194
}
195195
EXPECT_TRUE(caught);
196196
}
197+
198+
TEST(test_parser, test_parse_backslash)
199+
{
200+
std::error_code error;
201+
std::string json_string = "{\"bourne\":\"\\\\\"}";
202+
auto result = bourne::detail::parser::parse(json_string, error);
203+
ASSERT_FALSE((bool)error);
204+
EXPECT_EQ(json_string, result.dump_min());
205+
}
206+
207+
TEST(test_parser, test_parse_unicode)
208+
{
209+
std::error_code error;
210+
std::string json_string = "{\"bourne\":\"\\u0026\"}";
211+
auto result = bourne::detail::parser::parse(json_string, error);
212+
ASSERT_FALSE((bool)error);
213+
ASSERT_EQ(json_string, result.dump_min());
214+
}

0 commit comments

Comments
 (0)