From e3176df55d290f612089aa8af33a9f3f30f86456 Mon Sep 17 00:00:00 2001 From: t-k- Date: Thu, 25 Aug 2016 15:49:19 +0800 Subject: [PATCH] Expose a lower-level API for encoding C string. Add json_encode_string() as another API for directly encode C string into JSON string. --- parson.c | 16 ++++++++++++++++ parson.h | 1 + tests.c | 10 ++++++++++ 3 files changed, 27 insertions(+) diff --git a/parson.c b/parson.c index fc7621f..60c0aef 100644 --- a/parson.c +++ b/parson.c @@ -924,6 +924,22 @@ static int json_serialize_string(const char *string, char *buf) { return written_total; } +char *json_encode_string(const char *string) { + char *enc_str = NULL; + int buf_size_bytes = json_serialize_string(string, NULL); + + if (buf_size_bytes <= 0) { + return NULL; + } + + enc_str = (char*)malloc(buf_size_bytes + 1); + if (enc_str == NULL) + return NULL; + + json_serialize_string(string, enc_str); + return enc_str; +} + static int append_indent(char *buf, int level) { int i; int written = -1, written_total = 0; diff --git a/parson.h b/parson.h index 6a89982..6c2c55a 100644 --- a/parson.h +++ b/parson.h @@ -75,6 +75,7 @@ JSON_Value * json_parse_string(const char *string); JSON_Value * json_parse_string_with_comments(const char *string); /* Serialization */ +char * json_encode_string(const char *string); size_t json_serialization_size(const JSON_Value *value); /* returns 0 on fail */ JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes); JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename); diff --git a/tests.c b/tests.c index 819711d..4d4b78e 100644 --- a/tests.c +++ b/tests.c @@ -48,6 +48,7 @@ void test_suite_6(void); /* Test value comparing verification */ void test_suite_7(void); /* Test schema validation */ void test_suite_8(void); /* Test serialization */ void test_suite_9(void); /* Test serialization (pretty) */ +void test_suite_10(void); /* Test string encoding */ void print_commits_info(const char *username, const char *repo); void persistence_example(void); @@ -74,6 +75,7 @@ int main() { test_suite_7(); test_suite_8(); test_suite_9(); + test_suite_10(); printf("Tests failed: %d\n", tests_failed); printf("Tests passed: %d\n", tests_passed); return 0; @@ -465,6 +467,14 @@ void test_suite_9(void) { TEST(STREQ(file_contents, serialized)); } +void test_suite_10(void) { + const char *raw_str = "\"\\/\b\f\n\r\t\"test"; + char *enc_str = json_encode_string(raw_str); + + TEST(STREQ(enc_str, "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\\\"test\"")); + free(enc_str); +} + void print_commits_info(const char *username, const char *repo) { JSON_Value *root_value; JSON_Array *commits;