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>
23 #include <boost/next_prior.hpp>
24 #include <boost/algorithm/string.hpp>
26 #include <folly/Conv.h>
27 #include <folly/Range.h>
28 #include <folly/String.h>
29 #include <folly/Unicode.h>
30 #include <folly/portability/Constexpr.h>
34 //////////////////////////////////////////////////////////////////////
42 unsigned* indentLevel,
43 serialization_opts const* opts)
44 : out_(out), indentLevel_(indentLevel), opts_(*opts) {}
46 void operator()(dynamic const& v) const {
49 if (!opts_.allow_nan_inf &&
50 (std::isnan(v.asDouble()) || std::isinf(v.asDouble()))) {
51 throw std::runtime_error("folly::toJson: JSON object value was a "
54 toAppend(v.asDouble(), &out_, opts_.double_mode, opts_.double_num_digits);
56 case dynamic::INT64: {
57 auto intval = v.asInt();
58 if (opts_.javascript_safe) {
59 // Use folly::to to check that this integer can be represented
60 // as a double without loss of precision.
61 intval = int64_t(to<double>(intval));
63 toAppend(intval, &out_);
67 out_ += v.asBool() ? "true" : "false";
73 escapeString(v.asString(), out_, opts_);
82 CHECK(0) << "Bad type " << v.type();
87 void printKV(const std::pair<const dynamic, dynamic>& p) const {
88 if (!opts_.allow_non_string_keys && !p.first.isString()) {
89 throw std::runtime_error("folly::toJson: JSON object key was not a "
97 template <typename Iterator>
98 void printKVPairs(Iterator begin, Iterator end) const {
100 for (++begin; begin != end; ++begin) {
107 void printObject(dynamic const& o) const {
116 if (opts_.sort_keys) {
117 using ref = std::reference_wrapper<decltype(o.items())::value_type const>;
118 std::vector<ref> refs(o.items().begin(), o.items().end());
119 std::sort(refs.begin(), refs.end(), [](ref a, ref b) {
120 // Only compare keys. No ordering among identical keys.
121 return a.get().first < b.get().first;
123 printKVPairs(refs.cbegin(), refs.cend());
125 printKVPairs(o.items().begin(), o.items().end());
132 void printArray(dynamic const& a) const {
142 for (auto& val : range(boost::next(a.begin()), a.end())) {
153 void outdent() const {
159 void indent() const {
165 void newline() const {
167 out_ += to<std::string>('\n', std::string(*indentLevel_ * 2, ' '));
171 void mapColon() const {
172 out_ += indentLevel_ ? " : " : ":";
177 unsigned* const indentLevel_;
178 serialization_opts const& opts_;
181 //////////////////////////////////////////////////////////////////////
183 struct ParseError : std::runtime_error {
184 explicit ParseError(int line)
185 : std::runtime_error(to<std::string>("json parse error on line ", line))
188 explicit ParseError(int line, std::string const& context,
189 std::string const& expected)
190 : std::runtime_error(to<std::string>("json parse error on line ", line,
191 !context.empty() ? to<std::string>(" near `", context, '\'')
196 explicit ParseError(std::string const& msg)
197 : std::runtime_error("json parse error: " + msg)
201 // Wraps our input buffer with some helper functions.
203 explicit Input(StringPiece range, json::serialization_opts const* opts)
211 Input(Input const&) = delete;
212 Input& operator=(Input const&) = delete;
214 char const* begin() const { return range_.begin(); }
216 // Parse ahead for as long as the supplied predicate is satisfied,
217 // returning a range of what was skipped.
218 template<class Predicate>
219 StringPiece skipWhile(const Predicate& p) {
220 std::size_t skipped = 0;
221 for (; skipped < range_.size(); ++skipped) {
222 if (!p(range_[skipped])) {
225 if (range_[skipped] == '\n') {
229 auto ret = range_.subpiece(0, skipped);
230 range_.advance(skipped);
235 StringPiece skipDigits() {
236 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
239 StringPiece skipMinusAndDigits() {
240 bool firstChar = true;
241 return skipWhile([&firstChar] (char c) {
242 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
248 void skipWhitespace() {
249 range_ = folly::skipWhitespace(range_);
253 void expect(char c) {
255 throw ParseError(lineNum_, context(),
256 to<std::string>("expected '", c, '\''));
261 std::size_t size() const {
262 return range_.size();
265 int operator*() const {
277 return to<T>(&range_);
278 } catch (std::exception const& e) {
283 bool consume(StringPiece str) {
284 if (boost::starts_with(range_, str)) {
285 range_.advance(str.size());
292 std::string context() const {
293 return range_.subpiece(0, 16 /* arbitrary */).toString();
296 dynamic error(char const* what) const {
297 throw ParseError(lineNum_, context(), what);
300 json::serialization_opts const& getOpts() {
304 void incrementRecursionLevel() {
305 if (currentRecursionLevel_ > opts_.recursion_limit) {
306 error("recursion limit exceeded");
308 currentRecursionLevel_++;
311 void decrementRecursionLevel() {
312 currentRecursionLevel_--;
316 void storeCurrent() {
317 current_ = range_.empty() ? EOF : range_.front();
322 json::serialization_opts const& opts_;
325 unsigned int currentRecursionLevel_{0};
328 class RecursionGuard {
330 explicit RecursionGuard(Input& in) : in_(in) {
331 in_.incrementRecursionLevel();
335 in_.decrementRecursionLevel();
342 dynamic parseValue(Input& in);
343 std::string parseString(Input& in);
344 dynamic parseNumber(Input& in);
346 dynamic parseObject(Input& in) {
350 dynamic ret = dynamic::object;
359 if (in.getOpts().allow_trailing_comma && *in == '}') {
362 if (*in == '\"') { // string
363 auto key = parseString(in);
367 ret.insert(std::move(key), parseValue(in));
368 } else if (!in.getOpts().allow_non_string_keys) {
369 in.error("expected string for object key name");
371 auto key = parseValue(in);
375 ret.insert(std::move(key), parseValue(in));
390 dynamic parseArray(Input& in) {
394 dynamic ret = dynamic::array;
403 if (in.getOpts().allow_trailing_comma && *in == ']') {
406 ret.push_back(parseValue(in));
419 dynamic parseNumber(Input& in) {
420 bool const negative = (*in == '-');
421 if (negative && in.consume("-Infinity")) {
422 if (in.getOpts().parse_numbers_as_strings) {
425 return -std::numeric_limits<double>::infinity();
429 auto integral = in.skipMinusAndDigits();
430 if (negative && integral.size() < 2) {
431 in.error("expected digits after `-'");
434 auto const wasE = *in == 'e' || *in == 'E';
436 constexpr const char* maxInt = "9223372036854775807";
437 constexpr const char* minInt = "-9223372036854775808";
438 constexpr auto maxIntLen = constexpr_strlen(maxInt);
439 constexpr auto minIntLen = constexpr_strlen(minInt);
441 if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
445 if (*in != '.' && !wasE) {
446 if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
447 (!negative && integral.size() == maxIntLen && integral <= maxInt) ||
448 (negative && integral.size() == minIntLen && integral <= minInt)) {
449 auto val = to<int64_t>(integral);
453 auto val = to<double>(integral);
459 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
460 if (*in == 'e' || *in == 'E') {
462 if (*in == '+' || *in == '-') {
465 auto expPart = in.skipDigits();
468 auto fullNum = range(integral.begin(), end);
469 if (in.getOpts().parse_numbers_as_strings) {
472 auto val = to<double>(fullNum);
476 std::string decodeUnicodeEscape(Input& in) {
477 auto hexVal = [&] (int c) -> uint16_t {
479 c >= '0' && c <= '9' ? c - '0' :
480 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
481 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
482 (in.error("invalid hex digit"), 0));
485 auto readHex = [&]() -> uint16_t {
487 in.error("expected 4 hex digits");
490 uint16_t ret = uint16_t(hexVal(*in) * 4096);
492 ret += hexVal(*in) * 256;
494 ret += hexVal(*in) * 16;
502 * If the value encoded is in the surrogate pair range, we need to
503 * make sure there is another escape that we can use also.
505 uint32_t codePoint = readHex();
506 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
507 if (!in.consume("\\u")) {
508 in.error("expected another unicode escape for second half of "
511 uint16_t second = readHex();
512 if (second >= 0xdc00 && second <= 0xdfff) {
513 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
516 in.error("second character in surrogate pair is invalid");
518 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
519 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
522 return codePointToUtf8(codePoint);
525 std::string parseString(Input& in) {
531 auto range = in.skipWhile(
532 [] (char c) { return c != '\"' && c != '\\'; }
534 ret.append(range.begin(), range.end());
543 case '\"': ret.push_back('\"'); ++in; break;
544 case '\\': ret.push_back('\\'); ++in; break;
545 case '/': ret.push_back('/'); ++in; break;
546 case 'b': ret.push_back('\b'); ++in; break;
547 case 'f': ret.push_back('\f'); ++in; break;
548 case 'n': ret.push_back('\n'); ++in; break;
549 case 'r': ret.push_back('\r'); ++in; break;
550 case 't': ret.push_back('\t'); ++in; break;
551 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
553 in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
558 in.error("unterminated string");
562 * Apparently we're actually supposed to ban all control
563 * characters from strings. This seems unnecessarily
564 * restrictive, so we're only banning zero bytes. (Since the
565 * string is presumed to be UTF-8 encoded it's fine to just
568 in.error("null byte in string");
571 ret.push_back(char(*in));
578 dynamic parseValue(Input& in) {
579 RecursionGuard guard(in);
582 return *in == '[' ? parseArray(in) :
583 *in == '{' ? parseObject(in) :
584 *in == '\"' ? parseString(in) :
585 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
586 in.consume("true") ? true :
587 in.consume("false") ? false :
588 in.consume("null") ? nullptr :
589 in.consume("Infinity") ?
590 (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
591 (dynamic)std::numeric_limits<double>::infinity()) :
593 (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
594 (dynamic)std::numeric_limits<double>::quiet_NaN()) :
595 in.error("expected json value");
600 //////////////////////////////////////////////////////////////////////
602 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
604 unsigned indentLevel = 0;
605 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
610 // Escape a string so that it is legal to print it in JSON text.
614 const serialization_opts& opts) {
615 auto hexDigit = [] (uint8_t c) -> char {
616 return c < 10 ? c + '0' : c - 10 + 'a';
621 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
622 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
623 auto* e = reinterpret_cast<const unsigned char*>(input.end());
626 // Since non-ascii encoding inherently does utf8 validation
627 // we explicitly validate utf8 only if non-ascii encoding is disabled.
628 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
629 && !opts.encode_non_ascii) {
630 // to achieve better spatial and temporal coherence
631 // we do utf8 validation progressively along with the
632 // string-escaping instead of two separate passes
634 // as the encoding progresses, q will stay at or ahead of p
637 // as p catches up with q, move q forward
639 // calling utf8_decode has the side effect of
640 // checking that utf8 encodings are valid
641 char32_t v = utf8ToCodePoint(q, e, opts.skip_invalid_utf8);
642 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
643 out.append(u8"\ufffd");
649 if (opts.encode_non_ascii && (*p & 0x80)) {
650 // note that this if condition captures utf8 chars
651 // with value > 127, so size > 1 byte
652 char32_t v = utf8ToCodePoint(p, e, opts.skip_invalid_utf8);
654 out.push_back(hexDigit(uint8_t(v >> 12)));
655 out.push_back(hexDigit((v >> 8) & 0x0f));
656 out.push_back(hexDigit((v >> 4) & 0x0f));
657 out.push_back(hexDigit(v & 0x0f));
658 } else if (*p == '\\' || *p == '\"') {
660 out.push_back(char(*p++));
661 } else if (*p <= 0x1f) {
663 case '\b': out.append("\\b"); p++; break;
664 case '\f': out.append("\\f"); p++; break;
665 case '\n': out.append("\\n"); p++; break;
666 case '\r': out.append("\\r"); p++; break;
667 case '\t': out.append("\\t"); p++; break;
669 // note that this if condition captures non readable chars
670 // with value < 32, so size = 1 byte (e.g control chars).
672 out.push_back(hexDigit(uint8_t((*p & 0xf0) >> 4)));
673 out.push_back(hexDigit(uint8_t(*p & 0xf)));
677 out.push_back(char(*p++));
684 std::string stripComments(StringPiece jsonC) {
691 } state = State::None;
693 for (size_t i = 0; i < jsonC.size(); ++i) {
694 auto s = jsonC.subpiece(i);
697 if (s.startsWith("/*")) {
698 state = State::InlineComment;
701 } else if (s.startsWith("//")) {
702 state = State::LineComment;
705 } else if (s[0] == '\"') {
706 state = State::InString;
708 result.push_back(s[0]);
710 case State::InString:
712 if (UNLIKELY(s.size() == 1)) {
713 throw std::logic_error("Invalid JSONC: string is not terminated");
715 result.push_back(s[0]);
716 result.push_back(s[1]);
719 } else if (s[0] == '\"') {
722 result.push_back(s[0]);
724 case State::InlineComment:
725 if (s.startsWith("*/")) {
730 case State::LineComment:
732 // skip the line break. It doesn't matter.
737 throw std::logic_error("Unknown comment state");
745 //////////////////////////////////////////////////////////////////////
747 dynamic parseJson(StringPiece range) {
748 return parseJson(range, json::serialization_opts());
753 json::serialization_opts const& opts) {
755 json::Input in(range, &opts);
757 auto ret = parseValue(in);
759 if (in.size() && *in != '\0') {
760 in.error("parsing didn't consume all input");
765 std::string toJson(dynamic const& dyn) {
766 return json::serialize(dyn, json::serialization_opts());
769 std::string toPrettyJson(dynamic const& dyn) {
770 json::serialization_opts opts;
771 opts.pretty_formatting = true;
772 return json::serialize(dyn, opts);
775 //////////////////////////////////////////////////////////////////////
776 // dynamic::print_as_pseudo_json() is implemented here for header
777 // ordering reasons (most of the dynamic implementation is in
778 // dynamic-inl.h, which we don't want to include json.h).
780 void dynamic::print_as_pseudo_json(std::ostream& out) const {
781 json::serialization_opts opts;
782 opts.allow_non_string_keys = true;
783 opts.allow_nan_inf = true;
784 out << json::serialize(*this, opts);
787 void PrintTo(const dynamic& dyn, std::ostream* os) {
788 json::serialization_opts opts;
789 opts.allow_nan_inf = true;
790 opts.allow_non_string_keys = true;
791 opts.pretty_formatting = true;
792 opts.sort_keys = true;
793 *os << json::serialize(dyn, opts);
796 //////////////////////////////////////////////////////////////////////