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 {
186 std::string const& context,
187 std::string const& expected)
188 : std::runtime_error(to<std::string>(
189 "json parse error on line ",
191 !context.empty() ? to<std::string>(" near `", context, '\'') : "",
196 // Wraps our input buffer with some helper functions.
198 explicit Input(StringPiece range, json::serialization_opts const* opts)
206 Input(Input const&) = delete;
207 Input& operator=(Input const&) = delete;
209 char const* begin() const { return range_.begin(); }
211 // Parse ahead for as long as the supplied predicate is satisfied,
212 // returning a range of what was skipped.
213 template<class Predicate>
214 StringPiece skipWhile(const Predicate& p) {
215 std::size_t skipped = 0;
216 for (; skipped < range_.size(); ++skipped) {
217 if (!p(range_[skipped])) {
220 if (range_[skipped] == '\n') {
224 auto ret = range_.subpiece(0, skipped);
225 range_.advance(skipped);
230 StringPiece skipDigits() {
231 return skipWhile([] (char c) { return c >= '0' && c <= '9'; });
234 StringPiece skipMinusAndDigits() {
235 bool firstChar = true;
236 return skipWhile([&firstChar] (char c) {
237 bool result = (c >= '0' && c <= '9') || (firstChar && c == '-');
243 void skipWhitespace() {
244 range_ = folly::skipWhitespace(range_);
248 void expect(char c) {
250 throw ParseError(lineNum_, context(),
251 to<std::string>("expected '", c, '\''));
256 std::size_t size() const {
257 return range_.size();
260 int operator*() const {
272 return to<T>(&range_);
273 } catch (std::exception const& e) {
278 bool consume(StringPiece str) {
279 if (boost::starts_with(range_, str)) {
280 range_.advance(str.size());
287 std::string context() const {
288 return range_.subpiece(0, 16 /* arbitrary */).toString();
291 dynamic error(char const* what) const {
292 throw ParseError(lineNum_, context(), what);
295 json::serialization_opts const& getOpts() {
299 void incrementRecursionLevel() {
300 if (currentRecursionLevel_ > opts_.recursion_limit) {
301 error("recursion limit exceeded");
303 currentRecursionLevel_++;
306 void decrementRecursionLevel() {
307 currentRecursionLevel_--;
311 void storeCurrent() {
312 current_ = range_.empty() ? EOF : range_.front();
317 json::serialization_opts const& opts_;
320 unsigned int currentRecursionLevel_{0};
323 class RecursionGuard {
325 explicit RecursionGuard(Input& in) : in_(in) {
326 in_.incrementRecursionLevel();
330 in_.decrementRecursionLevel();
337 dynamic parseValue(Input& in);
338 std::string parseString(Input& in);
339 dynamic parseNumber(Input& in);
341 dynamic parseObject(Input& in) {
345 dynamic ret = dynamic::object;
354 if (in.getOpts().allow_trailing_comma && *in == '}') {
357 if (*in == '\"') { // string
358 auto key = parseString(in);
362 ret.insert(std::move(key), parseValue(in));
363 } else if (!in.getOpts().allow_non_string_keys) {
364 in.error("expected string for object key name");
366 auto key = parseValue(in);
370 ret.insert(std::move(key), parseValue(in));
385 dynamic parseArray(Input& in) {
389 dynamic ret = dynamic::array;
398 if (in.getOpts().allow_trailing_comma && *in == ']') {
401 ret.push_back(parseValue(in));
414 dynamic parseNumber(Input& in) {
415 bool const negative = (*in == '-');
416 if (negative && in.consume("-Infinity")) {
417 if (in.getOpts().parse_numbers_as_strings) {
420 return -std::numeric_limits<double>::infinity();
424 auto integral = in.skipMinusAndDigits();
425 if (negative && integral.size() < 2) {
426 in.error("expected digits after `-'");
429 auto const wasE = *in == 'e' || *in == 'E';
431 constexpr const char* maxInt = "9223372036854775807";
432 constexpr const char* minInt = "-9223372036854775808";
433 constexpr auto maxIntLen = constexpr_strlen(maxInt);
434 constexpr auto minIntLen = constexpr_strlen(minInt);
436 if (*in != '.' && !wasE && in.getOpts().parse_numbers_as_strings) {
440 if (*in != '.' && !wasE) {
441 if (LIKELY(!in.getOpts().double_fallback || integral.size() < maxIntLen) ||
442 (!negative && integral.size() == maxIntLen && integral <= maxInt) ||
443 (negative && integral.size() == minIntLen && integral <= minInt)) {
444 auto val = to<int64_t>(integral);
448 auto val = to<double>(integral);
454 auto end = !wasE ? (++in, in.skipDigits().end()) : in.begin();
455 if (*in == 'e' || *in == 'E') {
457 if (*in == '+' || *in == '-') {
460 auto expPart = in.skipDigits();
463 auto fullNum = range(integral.begin(), end);
464 if (in.getOpts().parse_numbers_as_strings) {
467 auto val = to<double>(fullNum);
471 std::string decodeUnicodeEscape(Input& in) {
472 auto hexVal = [&] (int c) -> uint16_t {
474 c >= '0' && c <= '9' ? c - '0' :
475 c >= 'a' && c <= 'f' ? c - 'a' + 10 :
476 c >= 'A' && c <= 'F' ? c - 'A' + 10 :
477 (in.error("invalid hex digit"), 0));
480 auto readHex = [&]() -> uint16_t {
482 in.error("expected 4 hex digits");
485 uint16_t ret = uint16_t(hexVal(*in) * 4096);
487 ret += hexVal(*in) * 256;
489 ret += hexVal(*in) * 16;
497 * If the value encoded is in the surrogate pair range, we need to
498 * make sure there is another escape that we can use also.
500 uint32_t codePoint = readHex();
501 if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
502 if (!in.consume("\\u")) {
503 in.error("expected another unicode escape for second half of "
506 uint16_t second = readHex();
507 if (second >= 0xdc00 && second <= 0xdfff) {
508 codePoint = 0x10000 + ((codePoint & 0x3ff) << 10) +
511 in.error("second character in surrogate pair is invalid");
513 } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
514 in.error("invalid unicode code point (in range [0xdc00,0xdfff])");
517 return codePointToUtf8(codePoint);
520 std::string parseString(Input& in) {
526 auto range = in.skipWhile(
527 [] (char c) { return c != '\"' && c != '\\'; }
529 ret.append(range.begin(), range.end());
538 case '\"': ret.push_back('\"'); ++in; break;
539 case '\\': ret.push_back('\\'); ++in; break;
540 case '/': ret.push_back('/'); ++in; break;
541 case 'b': ret.push_back('\b'); ++in; break;
542 case 'f': ret.push_back('\f'); ++in; break;
543 case 'n': ret.push_back('\n'); ++in; break;
544 case 'r': ret.push_back('\r'); ++in; break;
545 case 't': ret.push_back('\t'); ++in; break;
546 case 'u': ++in; ret += decodeUnicodeEscape(in); break;
548 in.error(to<std::string>("unknown escape ", *in, " in string").c_str());
553 in.error("unterminated string");
557 * Apparently we're actually supposed to ban all control
558 * characters from strings. This seems unnecessarily
559 * restrictive, so we're only banning zero bytes. (Since the
560 * string is presumed to be UTF-8 encoded it's fine to just
563 in.error("null byte in string");
566 ret.push_back(char(*in));
573 dynamic parseValue(Input& in) {
574 RecursionGuard guard(in);
577 return *in == '[' ? parseArray(in) :
578 *in == '{' ? parseObject(in) :
579 *in == '\"' ? parseString(in) :
580 (*in == '-' || (*in >= '0' && *in <= '9')) ? parseNumber(in) :
581 in.consume("true") ? true :
582 in.consume("false") ? false :
583 in.consume("null") ? nullptr :
584 in.consume("Infinity") ?
585 (in.getOpts().parse_numbers_as_strings ? (dynamic)"Infinity" :
586 (dynamic)std::numeric_limits<double>::infinity()) :
588 (in.getOpts().parse_numbers_as_strings ? (dynamic)"NaN" :
589 (dynamic)std::numeric_limits<double>::quiet_NaN()) :
590 in.error("expected json value");
595 //////////////////////////////////////////////////////////////////////
597 std::string serialize(dynamic const& dyn, serialization_opts const& opts) {
599 unsigned indentLevel = 0;
600 Printer p(ret, opts.pretty_formatting ? &indentLevel : nullptr, &opts);
605 // Escape a string so that it is legal to print it in JSON text.
609 const serialization_opts& opts) {
610 auto hexDigit = [] (uint8_t c) -> char {
611 return c < 10 ? c + '0' : c - 10 + 'a';
616 auto* p = reinterpret_cast<const unsigned char*>(input.begin());
617 auto* q = reinterpret_cast<const unsigned char*>(input.begin());
618 auto* e = reinterpret_cast<const unsigned char*>(input.end());
621 // Since non-ascii encoding inherently does utf8 validation
622 // we explicitly validate utf8 only if non-ascii encoding is disabled.
623 if ((opts.validate_utf8 || opts.skip_invalid_utf8)
624 && !opts.encode_non_ascii) {
625 // to achieve better spatial and temporal coherence
626 // we do utf8 validation progressively along with the
627 // string-escaping instead of two separate passes
629 // as the encoding progresses, q will stay at or ahead of p
632 // as p catches up with q, move q forward
634 // calling utf8_decode has the side effect of
635 // checking that utf8 encodings are valid
636 char32_t v = utf8ToCodePoint(q, e, opts.skip_invalid_utf8);
637 if (opts.skip_invalid_utf8 && v == U'\ufffd') {
638 out.append(u8"\ufffd");
644 if (opts.encode_non_ascii && (*p & 0x80)) {
645 // note that this if condition captures utf8 chars
646 // with value > 127, so size > 1 byte
647 char32_t v = utf8ToCodePoint(p, e, opts.skip_invalid_utf8);
649 out.push_back(hexDigit(uint8_t(v >> 12)));
650 out.push_back(hexDigit((v >> 8) & 0x0f));
651 out.push_back(hexDigit((v >> 4) & 0x0f));
652 out.push_back(hexDigit(v & 0x0f));
653 } else if (*p == '\\' || *p == '\"') {
655 out.push_back(char(*p++));
656 } else if (*p <= 0x1f) {
658 case '\b': out.append("\\b"); p++; break;
659 case '\f': out.append("\\f"); p++; break;
660 case '\n': out.append("\\n"); p++; break;
661 case '\r': out.append("\\r"); p++; break;
662 case '\t': out.append("\\t"); p++; break;
664 // note that this if condition captures non readable chars
665 // with value < 32, so size = 1 byte (e.g control chars).
667 out.push_back(hexDigit(uint8_t((*p & 0xf0) >> 4)));
668 out.push_back(hexDigit(uint8_t(*p & 0xf)));
672 out.push_back(char(*p++));
679 std::string stripComments(StringPiece jsonC) {
686 } state = State::None;
688 for (size_t i = 0; i < jsonC.size(); ++i) {
689 auto s = jsonC.subpiece(i);
692 if (s.startsWith("/*")) {
693 state = State::InlineComment;
696 } else if (s.startsWith("//")) {
697 state = State::LineComment;
700 } else if (s[0] == '\"') {
701 state = State::InString;
703 result.push_back(s[0]);
705 case State::InString:
707 if (UNLIKELY(s.size() == 1)) {
708 throw std::logic_error("Invalid JSONC: string is not terminated");
710 result.push_back(s[0]);
711 result.push_back(s[1]);
714 } else if (s[0] == '\"') {
717 result.push_back(s[0]);
719 case State::InlineComment:
720 if (s.startsWith("*/")) {
725 case State::LineComment:
727 // skip the line break. It doesn't matter.
732 throw std::logic_error("Unknown comment state");
740 //////////////////////////////////////////////////////////////////////
742 dynamic parseJson(StringPiece range) {
743 return parseJson(range, json::serialization_opts());
748 json::serialization_opts const& opts) {
750 json::Input in(range, &opts);
752 auto ret = parseValue(in);
754 if (in.size() && *in != '\0') {
755 in.error("parsing didn't consume all input");
760 std::string toJson(dynamic const& dyn) {
761 return json::serialize(dyn, json::serialization_opts());
764 std::string toPrettyJson(dynamic const& dyn) {
765 json::serialization_opts opts;
766 opts.pretty_formatting = true;
767 return json::serialize(dyn, opts);
770 //////////////////////////////////////////////////////////////////////
771 // dynamic::print_as_pseudo_json() is implemented here for header
772 // ordering reasons (most of the dynamic implementation is in
773 // dynamic-inl.h, which we don't want to include json.h).
775 void dynamic::print_as_pseudo_json(std::ostream& out) const {
776 json::serialization_opts opts;
777 opts.allow_non_string_keys = true;
778 opts.allow_nan_inf = true;
779 out << json::serialize(*this, opts);
782 void PrintTo(const dynamic& dyn, std::ostream* os) {
783 json::serialization_opts opts;
784 opts.allow_nan_inf = true;
785 opts.allow_non_string_keys = true;
786 opts.pretty_formatting = true;
787 opts.sort_keys = true;
788 *os << json::serialize(dyn, opts);
791 //////////////////////////////////////////////////////////////////////