2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/json.h>
19 #include <boost/next_prior.hpp>
20 #include <boost/algorithm/string.hpp>
22 #include <folly/Conv.h>
23 #include <folly/Portability.h>
24 #include <folly/Range.h>
25 #include <folly/String.h>
26 #include <folly/Unicode.h>
27 #include <folly/portability/Constexpr.h>
31 //////////////////////////////////////////////////////////////////////
39 unsigned* indentLevel,
40 serialization_opts const* opts)
41 : out_(out), indentLevel_(indentLevel), opts_(*opts) {}
43 void operator()(dynamic const& v) const {
46 if (!opts_.allow_nan_inf &&
47 (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
48 throw std::runtime_error("folly::toJson: JSON object value was a "
51 toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
53 case dynamic::INT64: {
54 auto intval = v.asInt();
55 if (opts_.javascript_safe) {
56 // Use folly::to to check that this integer can be represented
57 // as a double without loss of precision.
58 intval = int64_t(to<double>(intval));
60 toAppend(intval, &out_);
64 out_ += v.asBool() ? "true" : "false";
70 escapeString(v.asString(), out_, opts_);
79 CHECK(0) << "Bad type " << v.type();
84 void printKV(const std::pair<const dynamic, dynamic>& p) const {
85 if (!opts_.allow_non_string_keys && !p.first.isString()) {
86 throw std::runtime_error("folly::toJson: JSON object key was not a "
94 template <typename Iterator>
95 void printKVPairs(Iterator begin, Iterator end) const {
97 for (++begin; begin != end; ++begin) {
104 void printObject(dynamic const& o) const {
113 if (opts_.sort_keys) {
114 std::vector<std::pair<dynamic, dynamic>> items(
115 o.items().begin(), o.items().end());
116 std::sort(items.begin(), items.end());
117 printKVPairs(items.begin(), items.end());
119 printKVPairs(o.items().begin(), o.items().end());
126 void printArray(dynamic const& a) const {
136 for (auto& val : range(boost::next(a.begin()), a.end())) {
147 void outdent() const {
153 void indent() const {
159 void newline() const {
161 out_ += to<std::string>('\n', std::string(*indentLevel_ * 2, ' '));
165 void mapColon() const {
166 out_ += indentLevel_ ? " : " : ":";
171 unsigned* const indentLevel_;
172 serialization_opts const& opts_;
175 //////////////////////////////////////////////////////////////////////
177 struct ParseError : std::runtime_error {
178 explicit ParseError(int line)
179 : std::runtime_error(to<std::string>("json parse error on line ", line))
182 explicit ParseError(int line, std::string const& context,
183 std::string const& expected)
184 : std::runtime_error(to<std::string>("json parse error on line ", line,
185 !context.empty() ? to<std::string>(" near `", context, '\'')
190 explicit ParseError(std::string const& msg)
191 : std::runtime_error("json parse error: " + msg)
195 // Wraps our input buffer with some helper functions.
197 explicit Input(StringPiece range, json::serialization_opts const* opts)
205 Input(Input const&) = delete;
206 Input& operator=(Input const&) = delete;
208 char const* begin() const { return range_.begin(); }
210 // Parse ahead for as long as the supplied predicate is satisfied,
211 // returning a range of what was skipped.
212 template<class Predicate>
213 StringPiece skipWhile(const Predicate& p) {
214 std::size_t skipped = 0;
215 for (; skipped < range_.size(); ++skipped) {
216 if (!p(range_[skipped])) {
219 if (range_[skipped] == '\n') {
223 auto ret = range_.subpiece(0, skipped);
224 range_.advance(skipped);
229 StringPiece skipDigits() {
230 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
233 StringPiece skipMinusAndDigits() {
234 bool firstChar = true;
235 return skipWhile([&firstChar] (char c) {
236 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
242 void skipWhitespace() {
243 range_ = folly::skipWhitespace(range_);
247 void expect(char c) {
249 throw ParseError(lineNum_, context(),
250 to<std::string>("expected '", c, '\''));
255 std::size_t size() const {
256 return range_.size();
259 int operator*() const {
271 return to<T>(&range_);
272 } catch (std::exception const& e) {
277 bool consume(StringPiece str) {
278 if (boost::starts_with(range_, str)) {
279 range_.advance(str.size());
286 std::string context() const {
287 return range_.subpiece(0, 16 /* arbitrary */).toString();
290 dynamic error(char const* what) const {
291 throw ParseError(lineNum_, context(), what);
294 json::serialization_opts const& getOpts() {
298 void incrementRecursionLevel() {
299 if (currentRecursionLevel_ > opts_.recursion_limit) {
300 error("recursion limit exceeded");
302 currentRecursionLevel_++;
305 void decrementRecursionLevel() {
306 currentRecursionLevel_--;
310 void storeCurrent() {
311 current_ = range_.empty() ? EOF : range_.front();
316 json::serialization_opts const& opts_;
319 unsigned int currentRecursionLevel_{0};
322 class RecursionGuard {
324 explicit RecursionGuard(Input& in) : in_(in) {
325 in_.incrementRecursionLevel();
329 in_.decrementRecursionLevel();
336 dynamic parseValue(Input& in);
337 std::string parseString(Input& in);
338 dynamic parseNumber(Input& in);
340 dynamic parseObject(Input& in) {
344 dynamic ret = dynamic::object;
353 if (in.getOpts().allow_trailing_comma && *in == '}') {
356 if (*in == '\"') { // string
357 auto key = parseString(in);
361 ret.insert(std::move(key), parseValue(in));
362 } else if (!in.getOpts().allow_non_string_keys) {
363 in.error("expected string for object key name");
365 auto key = parseValue(in);
369 ret.insert(std::move(key), parseValue(in));
384 dynamic parseArray(Input& in) {
388 dynamic ret = dynamic::array;
397 if (in.getOpts().allow_trailing_comma && *in == ']') {
400 ret.push_back(parseValue(in));
413 dynamic parseNumber(Input& in) {
414 bool const negative = (*in == '-');
415 if (negative && in.consume("-Infinity")) {
416 if (in.getOpts().parse_numbers_as_strings) {
419 return -std::numeric_limits<double>::infinity();
423 auto integral = in.skipMinusAndDigits();
424 if (negative && integral.size() < 2) {
425 in.error("expected digits after `-'");
428 auto const wasE = *in == 'e' || *in == 'E';
430 constexpr const char* maxInt = "9223372036854775807";
431 constexpr const char* minInt = "-9223372036854775808";
432 constexpr auto maxIntLen = constexpr_strlen(maxInt);
433 constexpr auto minIntLen = constexpr_strlen(minInt);
435 if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
439 if (*in != '.' && !wasE) {
440 if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
441 (!negative && integral.size() == maxIntLen && integral <= maxInt) ||
442 (negative && integral.size() == minIntLen && integral <= minInt)) {
443 auto val = to<int64_t>(integral);
447 auto val = to<double>(integral);
453 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
454 if (*in == 'e' || *in == 'E') {
456 if (*in == '+' || *in == '-') {
459 auto expPart = in.skipDigits();
462 auto fullNum = range(integral.begin(), end);
463 if (in.getOpts().parse_numbers_as_strings) {
466 auto val = to<double>(fullNum);
470 std::string decodeUnicodeEscape(Input& in) {
471 auto hexVal = [&] (int c) -> uint16_t {
473 c >= '0' && c <= '9' ? c - '0' :
474 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
475 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
476 (in.error("invalid hex digit"), 0));
479 auto readHex = [&]() -> uint16_t {
481 in.error("expected 4 hex digits");
484 uint16_t ret = hexVal(*in) * 4096;
486 ret += hexVal(*in) * 256;
488 ret += hexVal(*in) * 16;
496 * If the value encoded is in the surrogate pair range, we need to
497 * make sure there is another escape that we can use also.
499 uint32_t codePoint = readHex();
500 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
501 if (!in.consume("\\u")) {
502 in.error("expected another unicode escape for second half of "
505 uint16_t second = readHex();
506 if (second >= 0xdc00 && second <= 0xdfff) {
507 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
510 in.error("second character in surrogate pair is invalid");
512 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
513 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
516 return codePointToUtf8(codePoint);
519 std::string parseString(Input& in) {
525 auto range = in.skipWhile(
526 [] (char c) { return c != '\"' && c != '\\'; }
528 ret.append(range.begin(), range.end());
537 case '\"': ret.push_back('\"'); ++in; break;
538 case '\\': ret.push_back('\\'); ++in; break;
539 case '/': ret.push_back('/'); ++in; break;
540 case 'b': ret.push_back('\b'); ++in; break;
541 case 'f': ret.push_back('\f'); ++in; break;
542 case 'n': ret.push_back('\n'); ++in; break;
543 case 'r': ret.push_back('\r'); ++in; break;
544 case 't': ret.push_back('\t'); ++in; break;
545 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
547 in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
552 in.error("unterminated string");
556 * Apparently we're actually supposed to ban all control
557 * characters from strings. This seems unnecessarily
558 * restrictive, so we're only banning zero bytes. (Since the
559 * string is presumed to be UTF-8 encoded it's fine to just
562 in.error("null byte in string");
565 ret.push_back(char(*in));
572 dynamic parseValue(Input& in) {
573 RecursionGuard guard(in);
576 return *in == '[' ? parseArray(in) :
577 *in == '{' ? parseObject(in) :
578 *in == '\"' ? parseString(in) :
579 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
580 in.consume("true") ? true :
581 in.consume("false") ? false :
582 in.consume("null") ? nullptr :
583 in.consume("Infinity") ?
584 (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
585 (dynamic)std::numeric_limits<double>::infinity()) :
587 (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
588 (dynamic)std::numeric_limits<double>::quiet_NaN()) :
589 in.error("expected json value");
594 //////////////////////////////////////////////////////////////////////
596 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
598 unsigned indentLevel = 0;
599 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
604 // Escape a string so that it is legal to print it in JSON text.
608 const serialization_opts& opts) {
609 auto hexDigit = [] (uint8_t c) -> char {
610 return c < 10 ? c + '0' : c - 10 + 'a';
615 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
616 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
617 auto* e = reinterpret_cast<const unsigned char*>(input.end());
620 // Since non-ascii encoding inherently does utf8 validation
621 // we explicitly validate utf8 only if non-ascii encoding is disabled.
622 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
623 && !opts.encode_non_ascii) {
624 // to achieve better spatial and temporal coherence
625 // we do utf8 validation progressively along with the
626 // string-escaping instead of two separate passes
628 // as the encoding progresses, q will stay at or ahead of p
631 // as p catches up with q, move q forward
633 // calling utf8_decode has the side effect of
634 // checking that utf8 encodings are valid
635 char32_t v = utf8ToCodePoint(q, e, opts.skip_invalid_utf8);
636 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
637 out.append(u8"\ufffd");
643 if (opts.encode_non_ascii && (*p & 0x80)) {
644 // note that this if condition captures utf8 chars
645 // with value > 127, so size > 1 byte
646 char32_t v = utf8ToCodePoint(p, e, opts.skip_invalid_utf8);
648 out.push_back(hexDigit(uint8_t(v >> 12)));
649 out.push_back(hexDigit((v >> 8) & 0x0f));
650 out.push_back(hexDigit((v >> 4) & 0x0f));
651 out.push_back(hexDigit(v & 0x0f));
652 } else if (*p == '\\' || *p == '\"') {
654 out.push_back(char(*p++));
655 } else if (*p <= 0x1f) {
657 case '\b': out.append("\\b"); p++; break;
658 case '\f': out.append("\\f"); p++; break;
659 case '\n': out.append("\\n"); p++; break;
660 case '\r': out.append("\\r"); p++; break;
661 case '\t': out.append("\\t"); p++; break;
663 // note that this if condition captures non readable chars
664 // with value < 32, so size = 1 byte (e.g control chars).
666 out.push_back(hexDigit((*p & 0xf0) >> 4));
667 out.push_back(hexDigit(*p & 0xf));
678 std::string stripComments(StringPiece jsonC) {
685 } state = State::None;
687 for (size_t i = 0; i < jsonC.size(); ++i) {
688 auto s = jsonC.subpiece(i);
691 if (s.startsWith("/*")) {
692 state = State::InlineComment;
695 } else if (s.startsWith("//")) {
696 state = State::LineComment;
699 } else if (s[0] == '\"') {
700 state = State::InString;
702 result.push_back(s[0]);
704 case State::InString:
706 if (UNLIKELY(s.size() == 1)) {
707 throw std::logic_error("Invalid JSONC: string is not terminated");
709 result.push_back(s[0]);
710 result.push_back(s[1]);
713 } else if (s[0] == '\"') {
716 result.push_back(s[0]);
718 case State::InlineComment:
719 if (s.startsWith("*/")) {
724 case State::LineComment:
726 // skip the line break. It doesn't matter.
731 throw std::logic_error("Unknown comment state");
739 //////////////////////////////////////////////////////////////////////
741 dynamic parseJson(StringPiece range) {
742 return parseJson(range, json::serialization_opts());
747 json::serialization_opts const& opts) {
749 json::Input in(range, &opts);
751 auto ret = parseValue(in);
753 if (in.size() && *in != '\0') {
754 in.error("parsing didn't consume all input");
759 std::string toJson(dynamic const& dyn) {
760 return json::serialize(dyn, json::serialization_opts());
763 std::string toPrettyJson(dynamic const& dyn) {
764 json::serialization_opts opts;
765 opts.pretty_formatting = true;
766 return json::serialize(dyn, opts);
769 //////////////////////////////////////////////////////////////////////
770 // dynamic::print_as_pseudo_json() is implemented here for header
771 // ordering reasons (most of the dynamic implementation is in
772 // dynamic-inl.h, which we don't want to include json.h).
774 void dynamic::print_as_pseudo_json(std::ostream& out) const {
775 json::serialization_opts opts;
776 opts.allow_non_string_keys = true;
777 opts.allow_nan_inf = true;
778 out << json::serialize(*this, opts);
781 void PrintTo(const dynamic& dyn, std::ostream* os) {
782 json::serialization_opts opts;
783 opts.allow_nan_inf = true;
784 opts.allow_non_string_keys = true;
785 opts.pretty_formatting = true;
786 opts.sort_keys = true;
787 *os << json::serialize(dyn, opts);
790 //////////////////////////////////////////////////////////////////////