├── docs ├── .gitignore ├── examples │ ├── nim.cfg │ ├── streamwrite0.nim │ ├── streamwrite1.nim │ ├── getstarted1.nim │ ├── getstarted0.nim │ ├── getstarted2.nim │ └── reference0.nim ├── open-in.css ├── src │ ├── SUMMARY.md │ ├── introduction.md │ ├── book.md │ ├── streaming.md │ ├── getting_started.md │ └── reference.md └── book.toml ├── tests ├── test_vectors │ ├── test_parsing │ │ ├── n_number_+1.json │ │ ├── n_number_0e.json │ │ ├── n_single_space.json │ │ ├── y_array_empty.json │ │ ├── y_number.json │ │ ├── y_object_empty.json │ │ ├── y_string_pi.json │ │ ├── n_array_just_comma.json │ │ ├── n_array_just_minus.json │ │ ├── n_array_unclosed.json │ │ ├── n_number_++.json │ │ ├── n_number_+Inf.json │ │ ├── n_number_-01.json │ │ ├── n_number_-1.0..json │ │ ├── n_number_-2..json │ │ ├── n_number_-NaN.json │ │ ├── n_number_.-1.json │ │ ├── n_number_.2e-3.json │ │ ├── n_number_0.1.2.json │ │ ├── n_number_0.3e+.json │ │ ├── n_number_0.3e.json │ │ ├── n_number_0.e1.json │ │ ├── n_number_0e+.json │ │ ├── n_number_1.0e+.json │ │ ├── n_number_1.0e-.json │ │ ├── n_number_1.0e.json │ │ ├── n_number_1eE2.json │ │ ├── n_number_2.e+3.json │ │ ├── n_number_2.e-3.json │ │ ├── n_number_2.e3.json │ │ ├── n_number_9.e+.json │ │ ├── n_number_Inf.json │ │ ├── n_number_NaN.json │ │ ├── n_object_emoji.json │ │ ├── n_object_no-colon.json │ │ ├── n_structure_no_data.json │ │ ├── y_array_false.json │ │ ├── y_array_null.json │ │ ├── y_number_0e+1.json │ │ ├── y_number_0e1.json │ │ ├── y_string_space.json │ │ ├── y_string_utf8.json │ │ ├── n_array_double_comma.json │ │ ├── n_array_extra_close.json │ │ ├── n_array_extra_comma.json │ │ ├── n_array_incomplete.json │ │ ├── n_array_star_inside.json │ │ ├── n_incomplete_false.json │ │ ├── n_incomplete_null.json │ │ ├── n_incomplete_true.json │ │ ├── n_number_0_capital_E+.json │ │ ├── n_number_0_capital_E.json │ │ ├── n_number_1_000.json │ │ ├── n_number_expression.json │ │ ├── n_number_hex_1_digit.json │ │ ├── n_number_invalid+-.json │ │ ├── n_object_missing_key.json │ │ ├── n_string_escape_x.json │ │ ├── n_structure_end_array.json │ │ ├── n_structure_open_object.json │ │ ├── n_structure_single_star.json │ │ ├── y_array_empty-string.json │ │ ├── y_number_after_space.json │ │ ├── y_number_minus_zero.json │ │ ├── y_number_negative_one.json │ │ ├── y_number_negative_zero.json │ │ ├── y_number_simple_int.json │ │ ├── y_object_empty_key.json │ │ ├── y_object_simple.json │ │ ├── y_string_in_array.json │ │ ├── y_string_unicode.json │ │ ├── y_string_unicode_2.json │ │ ├── y_structure_lonely_int.json │ │ ├── y_structure_string_empty.json │ │ ├── n_array_comma_after_close.json │ │ ├── n_array_comma_and_number.json │ │ ├── n_array_missing_value.json │ │ ├── n_array_number_and_comma.json │ │ ├── n_multidigit_number_then_00.json │ │ ├── n_number_hex_2_digits.json │ │ ├── n_number_infinity.json │ │ ├── n_number_minus_space_1.json │ │ ├── n_number_with_alpha.json │ │ ├── n_number_with_leading_zero.json │ │ ├── n_object_bad_value.json │ │ ├── n_object_double_colon.json │ │ ├── n_object_missing_colon.json │ │ ├── n_object_missing_value.json │ │ ├── n_object_non_string_key.json │ │ ├── n_object_single_quote.json │ │ ├── n_object_unquoted_key.json │ │ ├── n_string_backslash_00.json │ │ ├── n_string_escaped_emoji.json │ │ ├── n_string_incomplete_escape.json │ │ ├── n_string_single_doublequote.json │ │ ├── n_string_unescaped_tab.json │ │ ├── n_structure_UTF8_BOM_no_data.json │ │ ├── n_structure_angle_bracket_..json │ │ ├── n_structure_double_array.json │ │ ├── n_structure_lone-open-bracket.json │ │ ├── n_structure_open_array_comma.json │ │ ├── n_structure_open_object_comma.json │ │ ├── n_structure_unclosed_array.json │ │ ├── n_structure_unicode-identifier.json │ │ ├── y_array_arraysWithSpaces.json │ │ ├── y_array_with_leading_space.json │ │ ├── y_array_with_trailing_space.json │ │ ├── y_number_int_with_exp.json │ │ ├── y_number_negative_int.json │ │ ├── y_number_real_capital_e.json │ │ ├── y_number_real_exponent.json │ │ ├── y_number_real_neg_exp.json │ │ ├── y_object_basic.json │ │ ├── y_string_double_escape_a.json │ │ ├── y_string_double_escape_n.json │ │ ├── y_string_null_escape.json │ │ ├── y_string_simple_ascii.json │ │ ├── y_string_u+2028_line_sep.json │ │ ├── y_string_u+2029_par_sep.json │ │ ├── y_structure_lonely_false.json │ │ ├── y_structure_lonely_null.json │ │ ├── y_structure_lonely_string.json │ │ ├── y_structure_lonely_true.json │ │ ├── y_structure_true_in_array.json │ │ ├── i_number_neg_int_huge_exp.json │ │ ├── i_structure_UTF-8_BOM_empty_object.json │ │ ├── n_array_1_true_without_comma.json │ │ ├── n_array_double_extra_comma.json │ │ ├── n_array_incomplete_invalid_value.json │ │ ├── n_array_inner_array_no_comma.json │ │ ├── n_array_unclosed_trailing_comma.json │ │ ├── n_number_minus_infinity.json │ │ ├── n_number_real_garbage_after_e.json │ │ ├── n_number_starting_with_dot.json │ │ ├── n_object_bracket_key.json │ │ ├── n_object_garbage_at_end.json │ │ ├── n_object_missing_semicolon.json │ │ ├── n_object_trailing_comma.json │ │ ├── n_object_unterminated-value.json │ │ ├── n_string_escaped_ctrl_char_tab.json │ │ ├── n_string_invalid_backslash_esc.json │ │ ├── n_string_start_escape_unclosed.json │ │ ├── n_string_unescaped_ctrl_char.json │ │ ├── n_string_unicode_CapitalU.json │ │ ├── n_string_with_trailing_garbage.json │ │ ├── n_structure_U+2060_word_joined.json │ │ ├── n_structure_capitalized_True.json │ │ ├── n_structure_close_unopened_array.json │ │ ├── n_structure_open_array_apostrophe.json │ │ ├── n_structure_open_array_open_object.json │ │ ├── n_structure_open_array_string.json │ │ ├── n_structure_open_object_open_array.json │ │ ├── n_structure_trailing_#.json │ │ ├── n_structure_whitespace_formfeed.json │ │ ├── y_array_ending_with_newline.json │ │ ├── y_array_with_1_and_newline.json │ │ ├── y_number_real_pos_exponent.json │ │ ├── y_number_simple_real.json │ │ ├── y_object.json │ │ ├── y_string_comments.json │ │ ├── y_string_one-byte-utf-8.json │ │ ├── y_string_three-byte-utf-8.json │ │ ├── y_string_two-byte-utf-8.json │ │ ├── y_string_unescaped_char_delete.json │ │ ├── y_string_with_del_character.json │ │ ├── y_structure_lonely_negative_real.json │ │ ├── y_structure_whitespace_array.json │ │ ├── i_number_pos_double_huge_exp.json │ │ ├── i_number_real_pos_overflow.json │ │ ├── i_number_real_underflow.json │ │ ├── i_string_invalid_surrogate.json │ │ ├── i_string_lone_second_surrogate.json │ │ ├── n_array_colon_instead_of_comma.json │ │ ├── n_array_items_separated_by_semicolon.json │ │ ├── n_array_number_and_several_commas.json │ │ ├── n_array_unclosed_with_object_inside.json │ │ ├── n_number_U+FF11_fullwidth_digit_one.json │ │ ├── n_number_neg_int_starting_with_zero.json │ │ ├── n_number_neg_real_without_int_part.json │ │ ├── n_number_neg_with_garbage_at_end.json │ │ ├── n_number_real_without_fractional_part.json │ │ ├── n_object_trailing_comment.json │ │ ├── n_object_with_trailing_garbage.json │ │ ├── n_string_accentuated_char_no_quotes.json │ │ ├── n_string_escaped_backslash_bad.json │ │ ├── n_string_invalid_unicode_escape.json │ │ ├── n_string_no_quotes_with_bad_escape.json │ │ ├── n_string_single_quote.json │ │ ├── n_structure_angle_bracket_null.json │ │ ├── n_structure_array_trailing_garbage.json │ │ ├── n_structure_ascii-unicode-identifier.json │ │ ├── n_structure_null-byte-outside-string.json │ │ ├── n_structure_object_unclosed_no_value.json │ │ ├── n_structure_open_array_open_string.json │ │ ├── n_structure_open_object_close_array.json │ │ ├── n_structure_open_object_open_string.json │ │ ├── n_structure_open_open.json │ │ ├── n_structure_unclosed_object.json │ │ ├── y_array_heterogeneous.json │ │ ├── y_number_real_capital_e_neg_exp.json │ │ ├── y_number_real_capital_e_pos_exp.json │ │ ├── y_object_duplicated_key.json │ │ ├── y_string_backslash_doublequotes.json │ │ ├── y_string_escaped_noncharacter.json │ │ ├── y_string_nbsp_uescaped.json │ │ ├── y_string_nonCharacterInUTF-8_U+FFFF.json │ │ ├── y_string_unicode_U+FDD0_nonchar.json │ │ ├── y_string_unicode_U+FFFE_nonchar.json │ │ ├── y_structure_trailing_newline.json │ │ ├── i_number_double_huge_neg_exp.json │ │ ├── i_number_real_neg_overflow.json │ │ ├── i_object_key_lone_2nd_surrogate.json │ │ ├── i_string_incomplete_surrogate_pair.json │ │ ├── i_string_invalid_lonely_surrogate.json │ │ ├── n_array_newlines_unclosed.json │ │ ├── n_array_spaces_vertical_tab_formfeed.json │ │ ├── n_number_invalid-negative-real.json │ │ ├── n_object_comma_instead_of_colon.json │ │ ├── n_object_key_with_single_quotes.json │ │ ├── n_object_several_trailing_commas.json │ │ ├── n_object_trailing_comment_open.json │ │ ├── n_object_two_commas_in_a_row.json │ │ ├── n_string_1_surrogate_then_escape.json │ │ ├── n_string_1_surrogate_then_escape_u.json │ │ ├── n_string_incomplete_escaped_character.json │ │ ├── n_string_incomplete_surrogate.json │ │ ├── n_string_single_string_no_double_quotes.json │ │ ├── n_string_unescaped_newline.json │ │ ├── n_structure_array_with_extra_array_close.json │ │ ├── n_structure_array_with_unclosed_string.json │ │ ├── n_structure_number_with_trailing_garbage.json │ │ ├── n_structure_whitespace_U+2060_word_joiner.json │ │ ├── y_array_with_several_null.json │ │ ├── y_number_real_fraction_exponent.json │ │ ├── y_object_with_newlines.json │ │ ├── y_string_allowed_escapes.json │ │ ├── y_string_escaped_control_character.json │ │ ├── y_string_in_array_with_leading_space.json │ │ ├── y_string_nonCharacterInUTF-8_U+10FFFF.json │ │ ├── y_string_uEscape.json │ │ ├── y_string_uescaped_newline.json │ │ ├── y_string_unicodeEscapedBackslash.json │ │ ├── i_number_too_big_pos_int.json │ │ ├── i_string_1st_surrogate_but_2nd_missing.json │ │ ├── n_array_unclosed_with_new_lines.json │ │ ├── n_number_minus_sign_with_trailing_garbage.json │ │ ├── n_number_with_alpha_char.json │ │ ├── n_object_repeated_null_null.json │ │ ├── n_object_trailing_comment_slash_open.json │ │ ├── n_object_with_single_string.json │ │ ├── n_string_1_surrogate_then_escape_u1.json │ │ ├── n_string_1_surrogate_then_escape_u1x.json │ │ ├── n_string_leading_uescaped_thinspace.json │ │ ├── n_structure_object_followed_by_closing_object.json │ │ ├── n_structure_object_with_comment.json │ │ ├── n_structure_open_object_string_with_apostrophes.json │ │ ├── n_structure_uescaped_LF_before_string.json │ │ ├── n_structure_unclosed_array_partial_null.json │ │ ├── y_object_duplicated_key_and_value.json │ │ ├── y_object_escaped_null_in_key.json │ │ ├── y_string_accepted_surrogate_pair.json │ │ ├── y_string_backslash_and_u_escaped_zero.json │ │ ├── y_string_last_surrogates_1_and_2.json │ │ ├── y_string_reservedCharacterInUTF-8_U+1BFFF.json │ │ ├── y_string_unicode_U+10FFFE_nonchar.json │ │ ├── y_string_unicode_U+1FFFE_nonchar.json │ │ ├── y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json │ │ ├── y_string_unicode_U+2064_invisible_plus.json │ │ ├── y_string_unicode_escaped_double_quote.json │ │ ├── i_string_1st_valid_surrogate_2nd_invalid.json │ │ ├── i_string_inverted_surrogates_U+1D11E.json │ │ ├── n_structure_comma_instead_of_closing_brace.json │ │ ├── n_structure_object_with_trailing_garbage.json │ │ ├── n_structure_unclosed_array_unfinished_false.json │ │ ├── n_structure_unclosed_array_unfinished_true.json │ │ ├── i_number_too_big_neg_int.json │ │ ├── i_string_incomplete_surrogate_and_escape_valid.json │ │ ├── i_string_incomplete_surrogates_escape_valid.json │ │ ├── n_object_non_string_key_but_huge_number_instead.json │ │ ├── n_object_trailing_comment_slash_open_incomplete.json │ │ ├── y_object_extreme_numbers.json │ │ ├── y_string_1_2_3_bytes_UTF-8_sequences.json │ │ ├── y_string_accepted_surrogate_pairs.json │ │ ├── n_string_incomplete_surrogate_escape_invalid.json │ │ ├── y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json │ │ ├── i_number_very_big_negative_int.json │ │ ├── y_number_double_close_to_zero.json │ │ ├── y_object_long_strings.json │ │ ├── y_object_string_unicode.json │ │ ├── i_string_iso_latin_1.json │ │ ├── n_array_invalid_utf8.json │ │ ├── i_string_invalid_utf-8.json │ │ ├── i_string_utf16BE_no_BOM.json │ │ ├── i_string_utf16LE_no_BOM.json │ │ ├── n_array_a_invalid_utf8.json │ │ ├── i_number_huge_exp.json │ │ ├── i_string_truncated-utf-8.json │ │ ├── n_structure_single_eacute.json │ │ ├── i_string_UTF-16LE_with_BOM.json │ │ ├── i_string_UTF8_surrogate_U+D800.json │ │ ├── i_string_not_in_unicode_range.json │ │ ├── n_number_invalid-utf-8-in-int.json │ │ ├── n_structure_lone-invalid-utf-8.json │ │ ├── i_string_UTF-8_invalid_sequence.json │ │ ├── n_string_invalid-utf-8-in-escape.json │ │ ├── n_structure_incomplete_UTF8_BOM.json │ │ ├── i_string_overlong_sequence_2_bytes.json │ │ ├── i_string_overlong_sequence_6_bytes.json │ │ ├── n_number_invalid-utf-8-in-exponent.json │ │ ├── n_string_invalid_utf8_after_escape.json │ │ ├── i_string_lone_utf8_continuation_byte.json │ │ ├── n_number_invalid-utf-8-in-bigger-int.json │ │ ├── i_string_overlong_sequence_6_bytes_null.json │ │ ├── n_number_real_with_invalid_utf8_after_e.json │ │ ├── n_object_lone_continuation_byte_in_key_and_trailing_comma.json │ │ └── i_structure_500_nested_arrays.json │ ├── test_transform │ │ ├── number_1.0.json │ │ ├── number_1e6.json │ │ ├── number_1e-999.json │ │ ├── object_same_key_same_value.json │ │ ├── string_with_escaped_NULL.json │ │ ├── object_key_nfc_nfd.json │ │ ├── object_key_nfd_nfc.json │ │ ├── string_1_escaped_invalid_codepoint.json │ │ ├── number_1000000000000000.json │ │ ├── object_same_key_different_values.json │ │ ├── number_-9223372036854775808.json │ │ ├── number_-9223372036854775809.json │ │ ├── number_1.000000000000000005.json │ │ ├── number_10000000000000000999.json │ │ ├── number_9223372036854775807.json │ │ ├── number_9223372036854775808.json │ │ ├── object_same_key_unclear_values.json │ │ ├── string_2_escaped_invalid_codepoints.json │ │ ├── string_3_escaped_invalid_codepoints.json │ │ ├── string_1_invalid_codepoint.json │ │ ├── string_2_invalid_codepoints.json │ │ └── string_3_invalid_codepoints.json │ ├── LICENSE │ └── README.md ├── cases │ └── comments.json ├── nim.cfg ├── test_all.nim ├── utils.nim ├── test_spec.nim ├── test_line_col.nim ├── test_valueref.nim ├── test_json_flavor.nim ├── test_reader.nim ├── test_writer.nim └── test_parser.nim ├── .gitignore ├── .github └── workflows │ ├── ci.yml │ └── docs.yml ├── json_serialization ├── reader.nim ├── stew │ └── results.nim ├── std │ ├── uri.nim │ ├── sets.nim │ ├── net.nim │ ├── options.nim │ └── tables.nim ├── pkg │ ├── chronos.nim │ └── results.nim ├── types.nim ├── value_ops.nim ├── format.nim └── reader_desc.nim ├── json_serialization.nim ├── fuzzer ├── fuzz_lexer.nim ├── fuzz_parser.nim └── readme.md ├── LICENSE-MIT ├── config.nims ├── json_serialization.nimble ├── README.md └── LICENSE-APACHEv2 /docs/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /docs/examples/nim.cfg: -------------------------------------------------------------------------------- 1 | --path:"../.." -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_+1.json: -------------------------------------------------------------------------------- 1 | [+1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0e.json: -------------------------------------------------------------------------------- 1 | [0e] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_single_space.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_empty.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number.json: -------------------------------------------------------------------------------- 1 | [123e65] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_empty.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_pi.json: -------------------------------------------------------------------------------- 1 | ["π"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_just_comma.json: -------------------------------------------------------------------------------- 1 | [,] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_just_minus.json: -------------------------------------------------------------------------------- 1 | [-] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_unclosed.json: -------------------------------------------------------------------------------- 1 | ["" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_++.json: -------------------------------------------------------------------------------- 1 | [++1234] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_+Inf.json: -------------------------------------------------------------------------------- 1 | [+Inf] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_-01.json: -------------------------------------------------------------------------------- 1 | [-01] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_-1.0..json: -------------------------------------------------------------------------------- 1 | [-1.0.] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_-2..json: -------------------------------------------------------------------------------- 1 | [-2.] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_-NaN.json: -------------------------------------------------------------------------------- 1 | [-NaN] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_.-1.json: -------------------------------------------------------------------------------- 1 | [.-1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_.2e-3.json: -------------------------------------------------------------------------------- 1 | [.2e-3] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0.1.2.json: -------------------------------------------------------------------------------- 1 | [0.1.2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0.3e+.json: -------------------------------------------------------------------------------- 1 | [0.3e+] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0.3e.json: -------------------------------------------------------------------------------- 1 | [0.3e] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0.e1.json: -------------------------------------------------------------------------------- 1 | [0.e1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0e+.json: -------------------------------------------------------------------------------- 1 | [0e+] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_1.0e+.json: -------------------------------------------------------------------------------- 1 | [1.0e+] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_1.0e-.json: -------------------------------------------------------------------------------- 1 | [1.0e-] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_1.0e.json: -------------------------------------------------------------------------------- 1 | [1.0e] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_1eE2.json: -------------------------------------------------------------------------------- 1 | [1eE2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_2.e+3.json: -------------------------------------------------------------------------------- 1 | [2.e+3] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_2.e-3.json: -------------------------------------------------------------------------------- 1 | [2.e-3] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_2.e3.json: -------------------------------------------------------------------------------- 1 | [2.e3] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_9.e+.json: -------------------------------------------------------------------------------- 1 | [9.e+] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_Inf.json: -------------------------------------------------------------------------------- 1 | [Inf] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_NaN.json: -------------------------------------------------------------------------------- 1 | [NaN] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_emoji.json: -------------------------------------------------------------------------------- 1 | {🇨🇭} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_no-colon.json: -------------------------------------------------------------------------------- 1 | {"a" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_no_data.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_false.json: -------------------------------------------------------------------------------- 1 | [false] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_null.json: -------------------------------------------------------------------------------- 1 | [null] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_0e+1.json: -------------------------------------------------------------------------------- 1 | [0e+1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_0e1.json: -------------------------------------------------------------------------------- 1 | [0e1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_space.json: -------------------------------------------------------------------------------- 1 | " " -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_utf8.json: -------------------------------------------------------------------------------- 1 | ["€𝄞"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_double_comma.json: -------------------------------------------------------------------------------- 1 | [1,,2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_extra_close.json: -------------------------------------------------------------------------------- 1 | ["x"]] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_extra_comma.json: -------------------------------------------------------------------------------- 1 | ["",] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_incomplete.json: -------------------------------------------------------------------------------- 1 | ["x" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_star_inside.json: -------------------------------------------------------------------------------- 1 | [*] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_incomplete_false.json: -------------------------------------------------------------------------------- 1 | [fals] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_incomplete_null.json: -------------------------------------------------------------------------------- 1 | [nul] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_incomplete_true.json: -------------------------------------------------------------------------------- 1 | [tru] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0_capital_E+.json: -------------------------------------------------------------------------------- 1 | [0E+] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_0_capital_E.json: -------------------------------------------------------------------------------- 1 | [0E] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_1_000.json: -------------------------------------------------------------------------------- 1 | [1 000.0] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_expression.json: -------------------------------------------------------------------------------- 1 | [1+2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_hex_1_digit.json: -------------------------------------------------------------------------------- 1 | [0x1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_invalid+-.json: -------------------------------------------------------------------------------- 1 | [0e+-1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_missing_key.json: -------------------------------------------------------------------------------- 1 | {:"b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_escape_x.json: -------------------------------------------------------------------------------- 1 | ["\x00"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_end_array.json: -------------------------------------------------------------------------------- 1 | ] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object.json: -------------------------------------------------------------------------------- 1 | { -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_single_star.json: -------------------------------------------------------------------------------- 1 | * -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_empty-string.json: -------------------------------------------------------------------------------- 1 | [""] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_after_space.json: -------------------------------------------------------------------------------- 1 | [ 4] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_minus_zero.json: -------------------------------------------------------------------------------- 1 | [-0] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_negative_one.json: -------------------------------------------------------------------------------- 1 | [-1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_negative_zero.json: -------------------------------------------------------------------------------- 1 | [-0] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_simple_int.json: -------------------------------------------------------------------------------- 1 | [123] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_empty_key.json: -------------------------------------------------------------------------------- 1 | {"":0} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_simple.json: -------------------------------------------------------------------------------- 1 | {"a":[]} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_in_array.json: -------------------------------------------------------------------------------- 1 | ["asd"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode.json: -------------------------------------------------------------------------------- 1 | ["\uA66D"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_2.json: -------------------------------------------------------------------------------- 1 | ["⍂㈴⍂"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_int.json: -------------------------------------------------------------------------------- 1 | 42 -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_string_empty.json: -------------------------------------------------------------------------------- 1 | "" -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_1.0.json: -------------------------------------------------------------------------------- 1 | [1.0] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_1e6.json: -------------------------------------------------------------------------------- 1 | [1E6] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_comma_after_close.json: -------------------------------------------------------------------------------- 1 | [""], -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_comma_and_number.json: -------------------------------------------------------------------------------- 1 | [,1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_missing_value.json: -------------------------------------------------------------------------------- 1 | [ , ""] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_number_and_comma.json: -------------------------------------------------------------------------------- 1 | [1,] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_multidigit_number_then_00.json: -------------------------------------------------------------------------------- 1 | 123 -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_hex_2_digits.json: -------------------------------------------------------------------------------- 1 | [0x42] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_infinity.json: -------------------------------------------------------------------------------- 1 | [Infinity] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_minus_space_1.json: -------------------------------------------------------------------------------- 1 | [- 1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_with_alpha.json: -------------------------------------------------------------------------------- 1 | [1.2a-3] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_with_leading_zero.json: -------------------------------------------------------------------------------- 1 | [012] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_bad_value.json: -------------------------------------------------------------------------------- 1 | ["x", truth] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_double_colon.json: -------------------------------------------------------------------------------- 1 | {"x"::"b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_missing_colon.json: -------------------------------------------------------------------------------- 1 | {"a" b} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_missing_value.json: -------------------------------------------------------------------------------- 1 | {"a": -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_non_string_key.json: -------------------------------------------------------------------------------- 1 | {1:1} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_single_quote.json: -------------------------------------------------------------------------------- 1 | {'a':0} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_unquoted_key.json: -------------------------------------------------------------------------------- 1 | {a: "b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_backslash_00.json: -------------------------------------------------------------------------------- 1 | ["\"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_escaped_emoji.json: -------------------------------------------------------------------------------- 1 | ["\🌀"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_incomplete_escape.json: -------------------------------------------------------------------------------- 1 | ["\"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_single_doublequote.json: -------------------------------------------------------------------------------- 1 | " -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_unescaped_tab.json: -------------------------------------------------------------------------------- 1 | [" "] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_UTF8_BOM_no_data.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_angle_bracket_..json: -------------------------------------------------------------------------------- 1 | <.> -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_double_array.json: -------------------------------------------------------------------------------- 1 | [][] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_lone-open-bracket.json: -------------------------------------------------------------------------------- 1 | [ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_array_comma.json: -------------------------------------------------------------------------------- 1 | [, -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object_comma.json: -------------------------------------------------------------------------------- 1 | {, -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unclosed_array.json: -------------------------------------------------------------------------------- 1 | [1 -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unicode-identifier.json: -------------------------------------------------------------------------------- 1 | å -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_arraysWithSpaces.json: -------------------------------------------------------------------------------- 1 | [[] ] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_with_leading_space.json: -------------------------------------------------------------------------------- 1 | [1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_with_trailing_space.json: -------------------------------------------------------------------------------- 1 | [2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_int_with_exp.json: -------------------------------------------------------------------------------- 1 | [20e1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_negative_int.json: -------------------------------------------------------------------------------- 1 | [-123] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_capital_e.json: -------------------------------------------------------------------------------- 1 | [1E22] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_exponent.json: -------------------------------------------------------------------------------- 1 | [123e45] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_neg_exp.json: -------------------------------------------------------------------------------- 1 | [1e-2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_basic.json: -------------------------------------------------------------------------------- 1 | {"asd":"sdf"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_double_escape_a.json: -------------------------------------------------------------------------------- 1 | ["\\a"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_double_escape_n.json: -------------------------------------------------------------------------------- 1 | ["\\n"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_null_escape.json: -------------------------------------------------------------------------------- 1 | ["\u0000"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_simple_ascii.json: -------------------------------------------------------------------------------- 1 | ["asd "] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_u+2028_line_sep.json: -------------------------------------------------------------------------------- 1 | ["
"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_u+2029_par_sep.json: -------------------------------------------------------------------------------- 1 | ["
"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_false.json: -------------------------------------------------------------------------------- 1 | false -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_null.json: -------------------------------------------------------------------------------- 1 | null -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_string.json: -------------------------------------------------------------------------------- 1 | "asd" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_true.json: -------------------------------------------------------------------------------- 1 | true -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_true_in_array.json: -------------------------------------------------------------------------------- 1 | [true] -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_1e-999.json: -------------------------------------------------------------------------------- 1 | [1E-999] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_neg_int_huge_exp.json: -------------------------------------------------------------------------------- 1 | [-1e+9999] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_structure_UTF-8_BOM_empty_object.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_1_true_without_comma.json: -------------------------------------------------------------------------------- 1 | [1 true] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_double_extra_comma.json: -------------------------------------------------------------------------------- 1 | ["x",,] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_incomplete_invalid_value.json: -------------------------------------------------------------------------------- 1 | [x -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_inner_array_no_comma.json: -------------------------------------------------------------------------------- 1 | [3[4]] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_unclosed_trailing_comma.json: -------------------------------------------------------------------------------- 1 | [1, -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_minus_infinity.json: -------------------------------------------------------------------------------- 1 | [-Infinity] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_real_garbage_after_e.json: -------------------------------------------------------------------------------- 1 | [1ea] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_starting_with_dot.json: -------------------------------------------------------------------------------- 1 | [.123] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_bracket_key.json: -------------------------------------------------------------------------------- 1 | {[: "x"} 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_garbage_at_end.json: -------------------------------------------------------------------------------- 1 | {"a":"a" 123} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_missing_semicolon.json: -------------------------------------------------------------------------------- 1 | {"a" "b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_trailing_comma.json: -------------------------------------------------------------------------------- 1 | {"id":0,} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_unterminated-value.json: -------------------------------------------------------------------------------- 1 | {"a":"a -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_escaped_ctrl_char_tab.json: -------------------------------------------------------------------------------- 1 | ["\ "] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_invalid_backslash_esc.json: -------------------------------------------------------------------------------- 1 | ["\a"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_start_escape_unclosed.json: -------------------------------------------------------------------------------- 1 | ["\ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_unescaped_ctrl_char.json: -------------------------------------------------------------------------------- 1 | ["aa"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_unicode_CapitalU.json: -------------------------------------------------------------------------------- 1 | "\UA66D" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_with_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | ""x -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_U+2060_word_joined.json: -------------------------------------------------------------------------------- 1 | [⁠] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_capitalized_True.json: -------------------------------------------------------------------------------- 1 | [True] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_close_unopened_array.json: -------------------------------------------------------------------------------- 1 | 1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_array_apostrophe.json: -------------------------------------------------------------------------------- 1 | [' -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_array_open_object.json: -------------------------------------------------------------------------------- 1 | [{ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_array_string.json: -------------------------------------------------------------------------------- 1 | ["a" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object_open_array.json: -------------------------------------------------------------------------------- 1 | {[ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_trailing_#.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}#{} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_whitespace_formfeed.json: -------------------------------------------------------------------------------- 1 | [ ] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_ending_with_newline.json: -------------------------------------------------------------------------------- 1 | ["a"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_with_1_and_newline.json: -------------------------------------------------------------------------------- 1 | [1 2 | ] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_pos_exponent.json: -------------------------------------------------------------------------------- 1 | [1e+2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_simple_real.json: -------------------------------------------------------------------------------- 1 | [123.456789] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object.json: -------------------------------------------------------------------------------- 1 | {"asd":"sdf", "dfg":"fgh"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_comments.json: -------------------------------------------------------------------------------- 1 | ["a/*b*/c/*d//e"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_one-byte-utf-8.json: -------------------------------------------------------------------------------- 1 | ["\u002c"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_three-byte-utf-8.json: -------------------------------------------------------------------------------- 1 | ["\u0821"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_two-byte-utf-8.json: -------------------------------------------------------------------------------- 1 | ["\u0123"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unescaped_char_delete.json: -------------------------------------------------------------------------------- 1 | [""] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_with_del_character.json: -------------------------------------------------------------------------------- 1 | ["aa"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_lonely_negative_real.json: -------------------------------------------------------------------------------- 1 | -0.1 -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_whitespace_array.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_pos_double_huge_exp.json: -------------------------------------------------------------------------------- 1 | [1.5e+9999] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_real_pos_overflow.json: -------------------------------------------------------------------------------- 1 | [123123e100000] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_real_underflow.json: -------------------------------------------------------------------------------- 1 | [123e-10000000] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_invalid_surrogate.json: -------------------------------------------------------------------------------- 1 | ["\ud800abc"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_lone_second_surrogate.json: -------------------------------------------------------------------------------- 1 | ["\uDFAA"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_colon_instead_of_comma.json: -------------------------------------------------------------------------------- 1 | ["": 1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_items_separated_by_semicolon.json: -------------------------------------------------------------------------------- 1 | [1:2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_number_and_several_commas.json: -------------------------------------------------------------------------------- 1 | [1,,] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_unclosed_with_object_inside.json: -------------------------------------------------------------------------------- 1 | [{} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_U+FF11_fullwidth_digit_one.json: -------------------------------------------------------------------------------- 1 | [1] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_neg_int_starting_with_zero.json: -------------------------------------------------------------------------------- 1 | [-012] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_neg_real_without_int_part.json: -------------------------------------------------------------------------------- 1 | [-.123] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_neg_with_garbage_at_end.json: -------------------------------------------------------------------------------- 1 | [-1x] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_real_without_fractional_part.json: -------------------------------------------------------------------------------- 1 | [1.] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_trailing_comment.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}/**/ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_with_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}# -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_accentuated_char_no_quotes.json: -------------------------------------------------------------------------------- 1 | [é] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_escaped_backslash_bad.json: -------------------------------------------------------------------------------- 1 | ["\\\"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_invalid_unicode_escape.json: -------------------------------------------------------------------------------- 1 | ["\uqqqq"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_no_quotes_with_bad_escape.json: -------------------------------------------------------------------------------- 1 | [\n] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_single_quote.json: -------------------------------------------------------------------------------- 1 | ['single quote'] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_angle_bracket_null.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_array_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | [1]x -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_ascii-unicode-identifier.json: -------------------------------------------------------------------------------- 1 | aå -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_null-byte-outside-string.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_object_unclosed_no_value.json: -------------------------------------------------------------------------------- 1 | {"": -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_array_open_string.json: -------------------------------------------------------------------------------- 1 | ["a -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object_close_array.json: -------------------------------------------------------------------------------- 1 | {] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object_open_string.json: -------------------------------------------------------------------------------- 1 | {"a -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_open.json: -------------------------------------------------------------------------------- 1 | ["\{["\{["\{["\{ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unclosed_object.json: -------------------------------------------------------------------------------- 1 | {"asd":"asd" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_heterogeneous.json: -------------------------------------------------------------------------------- 1 | [null, 1, "1", {}] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_capital_e_neg_exp.json: -------------------------------------------------------------------------------- 1 | [1E-2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_capital_e_pos_exp.json: -------------------------------------------------------------------------------- 1 | [1E+2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_duplicated_key.json: -------------------------------------------------------------------------------- 1 | {"a":"b","a":"c"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_backslash_doublequotes.json: -------------------------------------------------------------------------------- 1 | ["\""] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_escaped_noncharacter.json: -------------------------------------------------------------------------------- 1 | ["\uFFFF"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_nbsp_uescaped.json: -------------------------------------------------------------------------------- 1 | ["new\u00A0line"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_nonCharacterInUTF-8_U+FFFF.json: -------------------------------------------------------------------------------- 1 | ["￿"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+FDD0_nonchar.json: -------------------------------------------------------------------------------- 1 | ["\uFDD0"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+FFFE_nonchar.json: -------------------------------------------------------------------------------- 1 | ["\uFFFE"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_structure_trailing_newline.json: -------------------------------------------------------------------------------- 1 | ["a"] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/object_same_key_same_value.json: -------------------------------------------------------------------------------- 1 | {"a":1,"a":1} -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_with_escaped_NULL.json: -------------------------------------------------------------------------------- 1 | ["A\u0000B"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_double_huge_neg_exp.json: -------------------------------------------------------------------------------- 1 | [123.456e-789] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_real_neg_overflow.json: -------------------------------------------------------------------------------- 1 | [-123123e100000] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_object_key_lone_2nd_surrogate.json: -------------------------------------------------------------------------------- 1 | {"\uDFAA":0} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_incomplete_surrogate_pair.json: -------------------------------------------------------------------------------- 1 | ["\uDd1ea"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_invalid_lonely_surrogate.json: -------------------------------------------------------------------------------- 1 | ["\ud800"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_newlines_unclosed.json: -------------------------------------------------------------------------------- 1 | ["a", 2 | 4 3 | ,1, -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_spaces_vertical_tab_formfeed.json: -------------------------------------------------------------------------------- 1 | [" a"\f] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_invalid-negative-real.json: -------------------------------------------------------------------------------- 1 | [-123.123foo] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_comma_instead_of_colon.json: -------------------------------------------------------------------------------- 1 | {"x", null} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_key_with_single_quotes.json: -------------------------------------------------------------------------------- 1 | {key: 'value'} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_several_trailing_commas.json: -------------------------------------------------------------------------------- 1 | {"id":0,,,,,} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_trailing_comment_open.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}/**// -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_two_commas_in_a_row.json: -------------------------------------------------------------------------------- 1 | {"a":"b",,"c":"d"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_1_surrogate_then_escape.json: -------------------------------------------------------------------------------- 1 | ["\uD800\"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_1_surrogate_then_escape_u.json: -------------------------------------------------------------------------------- 1 | ["\uD800\u"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_incomplete_escaped_character.json: -------------------------------------------------------------------------------- 1 | ["\u00A"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_incomplete_surrogate.json: -------------------------------------------------------------------------------- 1 | ["\uD834\uDd"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_single_string_no_double_quotes.json: -------------------------------------------------------------------------------- 1 | abc -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_unescaped_newline.json: -------------------------------------------------------------------------------- 1 | ["new 2 | line"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_array_with_extra_array_close.json: -------------------------------------------------------------------------------- 1 | [1]] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_array_with_unclosed_string.json: -------------------------------------------------------------------------------- 1 | ["asd] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_number_with_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | 2@ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_whitespace_U+2060_word_joiner.json: -------------------------------------------------------------------------------- 1 | [⁠] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_array_with_several_null.json: -------------------------------------------------------------------------------- 1 | [1,null,null,null,2] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_real_fraction_exponent.json: -------------------------------------------------------------------------------- 1 | [123.456e78] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_with_newlines.json: -------------------------------------------------------------------------------- 1 | { 2 | "a": "b" 3 | } -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_allowed_escapes.json: -------------------------------------------------------------------------------- 1 | ["\"\\\/\b\f\n\r\t"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_escaped_control_character.json: -------------------------------------------------------------------------------- 1 | ["\u0012"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_in_array_with_leading_space.json: -------------------------------------------------------------------------------- 1 | [ "asd"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_nonCharacterInUTF-8_U+10FFFF.json: -------------------------------------------------------------------------------- 1 | ["􏿿"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_uEscape.json: -------------------------------------------------------------------------------- 1 | ["\u0061\u30af\u30EA\u30b9"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_uescaped_newline.json: -------------------------------------------------------------------------------- 1 | ["new\u000Aline"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicodeEscapedBackslash.json: -------------------------------------------------------------------------------- 1 | ["\u005C"] -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/object_key_nfc_nfd.json: -------------------------------------------------------------------------------- 1 | {"é":"NFC","é":"NFD"} -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/object_key_nfd_nfc.json: -------------------------------------------------------------------------------- 1 | {"é":"NFD","é":"NFC"} -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_1_escaped_invalid_codepoint.json: -------------------------------------------------------------------------------- 1 | ["\uD800"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_too_big_pos_int.json: -------------------------------------------------------------------------------- 1 | [100000000000000000000] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_1st_surrogate_but_2nd_missing.json: -------------------------------------------------------------------------------- 1 | ["\uDADA"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_unclosed_with_new_lines.json: -------------------------------------------------------------------------------- 1 | [1, 2 | 1 3 | ,1 -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_minus_sign_with_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | [-foo] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_with_alpha_char.json: -------------------------------------------------------------------------------- 1 | [1.8011670033376514H-308] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_repeated_null_null.json: -------------------------------------------------------------------------------- 1 | {null:null,null:null} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_trailing_comment_slash_open.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}// -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_with_single_string.json: -------------------------------------------------------------------------------- 1 | { "foo" : "bar", "a" } -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_1_surrogate_then_escape_u1.json: -------------------------------------------------------------------------------- 1 | ["\uD800\u1"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_1_surrogate_then_escape_u1x.json: -------------------------------------------------------------------------------- 1 | ["\uD800\u1x"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_leading_uescaped_thinspace.json: -------------------------------------------------------------------------------- 1 | [\u0020"asd"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_object_followed_by_closing_object.json: -------------------------------------------------------------------------------- 1 | {}} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_object_with_comment.json: -------------------------------------------------------------------------------- 1 | {"a":/*comment*/"b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_open_object_string_with_apostrophes.json: -------------------------------------------------------------------------------- 1 | {'a' -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_uescaped_LF_before_string.json: -------------------------------------------------------------------------------- 1 | [\u000A""] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unclosed_array_partial_null.json: -------------------------------------------------------------------------------- 1 | [ false, nul -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_duplicated_key_and_value.json: -------------------------------------------------------------------------------- 1 | {"a":"b","a":"b"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_escaped_null_in_key.json: -------------------------------------------------------------------------------- 1 | {"foo\u0000bar": 42} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_accepted_surrogate_pair.json: -------------------------------------------------------------------------------- 1 | ["\uD801\udc37"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_backslash_and_u_escaped_zero.json: -------------------------------------------------------------------------------- 1 | ["\\u0000"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_last_surrogates_1_and_2.json: -------------------------------------------------------------------------------- 1 | ["\uDBFF\uDFFF"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_reservedCharacterInUTF-8_U+1BFFF.json: -------------------------------------------------------------------------------- 1 | ["𛿿"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+10FFFE_nonchar.json: -------------------------------------------------------------------------------- 1 | ["\uDBFF\uDFFE"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+1FFFE_nonchar.json: -------------------------------------------------------------------------------- 1 | ["\uD83F\uDFFE"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+200B_ZERO_WIDTH_SPACE.json: -------------------------------------------------------------------------------- 1 | ["\u200B"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_U+2064_invisible_plus.json: -------------------------------------------------------------------------------- 1 | ["\u2064"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_unicode_escaped_double_quote.json: -------------------------------------------------------------------------------- 1 | ["\u0022"] -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_1000000000000000.json: -------------------------------------------------------------------------------- 1 | [1000000000000000] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/object_same_key_different_values.json: -------------------------------------------------------------------------------- 1 | {"a":1,"a":2} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_1st_valid_surrogate_2nd_invalid.json: -------------------------------------------------------------------------------- 1 | ["\uD888\u1234"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_inverted_surrogates_U+1D11E.json: -------------------------------------------------------------------------------- 1 | ["\uDd1e\uD834"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_comma_instead_of_closing_brace.json: -------------------------------------------------------------------------------- 1 | {"x": true, -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_object_with_trailing_garbage.json: -------------------------------------------------------------------------------- 1 | {"a": true} "x" -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unclosed_array_unfinished_false.json: -------------------------------------------------------------------------------- 1 | [ true, fals -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_unclosed_array_unfinished_true.json: -------------------------------------------------------------------------------- 1 | [ false, tru -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_-9223372036854775808.json: -------------------------------------------------------------------------------- 1 | [-9223372036854775808] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_-9223372036854775809.json: -------------------------------------------------------------------------------- 1 | [-9223372036854775809] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_1.000000000000000005.json: -------------------------------------------------------------------------------- 1 | [1.000000000000000005] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_10000000000000000999.json: -------------------------------------------------------------------------------- 1 | [10000000000000000999] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_9223372036854775807.json: -------------------------------------------------------------------------------- 1 | [9223372036854775807] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/number_9223372036854775808.json: -------------------------------------------------------------------------------- 1 | [9223372036854775808] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/object_same_key_unclear_values.json: -------------------------------------------------------------------------------- 1 | {"a":0, "a":-0} 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_2_escaped_invalid_codepoints.json: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_too_big_neg_int.json: -------------------------------------------------------------------------------- 1 | [-123123123123123123123123123123] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_incomplete_surrogate_and_escape_valid.json: -------------------------------------------------------------------------------- 1 | ["\uD800\n"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_incomplete_surrogates_escape_valid.json: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800\n"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_non_string_key_but_huge_number_instead.json: -------------------------------------------------------------------------------- 1 | {9999E9999:1} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_trailing_comment_slash_open_incomplete.json: -------------------------------------------------------------------------------- 1 | {"a":"b"}/ -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_extreme_numbers.json: -------------------------------------------------------------------------------- 1 | { "min": -1.0e+28, "max": 1.0e+28 } -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_1_2_3_bytes_UTF-8_sequences.json: -------------------------------------------------------------------------------- 1 | ["\u0060\u012a\u12AB"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_accepted_surrogate_pairs.json: -------------------------------------------------------------------------------- 1 | ["\ud83d\ude39\ud83d\udc8d"] -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_3_escaped_invalid_codepoints.json: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800\uD800"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_incomplete_surrogate_escape_invalid.json: -------------------------------------------------------------------------------- 1 | ["\uD800\uD800\x"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_string_surrogates_U+1D11E_MUSICAL_SYMBOL_G_CLEF.json: -------------------------------------------------------------------------------- 1 | ["\uD834\uDd1e"] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_very_big_negative_int.json: -------------------------------------------------------------------------------- 1 | [-237462374673276894279832749832423479823246327846] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | nimcache 2 | *.exe 3 | nimble.develop 4 | nimble-win.paths 5 | nimble-linux.paths 6 | build/ 7 | vendor/ 8 | -------------------------------------------------------------------------------- /docs/open-in.css: -------------------------------------------------------------------------------- 1 | footer { 2 | font-size: 0.8em; 3 | text-align: center; 4 | border-top: 1px solid black; 5 | padding: 5px 0; 6 | } 7 | 8 | -------------------------------------------------------------------------------- /tests/cases/comments.json: -------------------------------------------------------------------------------- 1 | /* comments */ 2 | { 3 | "tasks": [ 4 | { 5 | "label": "nimbus-eth2 build" 6 | } 7 | ] // another commet 8 | } 9 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_number_double_close_to_zero.json: -------------------------------------------------------------------------------- 1 | [-0.000000000000000000000000000000000000000000000000000000000000000000000000000001] 2 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_long_strings.json: -------------------------------------------------------------------------------- 1 | {"x":[{"id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}], "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"} -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/y_object_string_unicode.json: -------------------------------------------------------------------------------- 1 | {"title":"\u041f\u043e\u043b\u0442\u043e\u0440\u0430 \u0417\u0435\u043c\u043b\u0435\u043a\u043e\u043f\u0430" } -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_iso_latin_1.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_iso_latin_1.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_invalid_utf8.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_array_invalid_utf8.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_invalid_utf-8.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_invalid_utf-8.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_utf16BE_no_BOM.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_utf16BE_no_BOM.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_utf16LE_no_BOM.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_utf16LE_no_BOM.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_array_a_invalid_utf8.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_array_a_invalid_utf8.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_number_huge_exp.json: -------------------------------------------------------------------------------- 1 | [0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006] -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_truncated-utf-8.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_truncated-utf-8.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_single_eacute.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_structure_single_eacute.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_UTF-16LE_with_BOM.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_UTF-16LE_with_BOM.json -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_1_invalid_codepoint.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_transform/string_1_invalid_codepoint.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_UTF8_surrogate_U+D800.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_UTF8_surrogate_U+D800.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_not_in_unicode_range.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_not_in_unicode_range.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-int.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-int.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_lone-invalid-utf-8.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_structure_lone-invalid-utf-8.json -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_2_invalid_codepoints.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_transform/string_2_invalid_codepoints.json -------------------------------------------------------------------------------- /tests/test_vectors/test_transform/string_3_invalid_codepoints.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_transform/string_3_invalid_codepoints.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_UTF-8_invalid_sequence.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_UTF-8_invalid_sequence.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_invalid-utf-8-in-escape.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_string_invalid-utf-8-in-escape.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_structure_incomplete_UTF8_BOM.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_structure_incomplete_UTF8_BOM.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_overlong_sequence_2_bytes.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_overlong_sequence_2_bytes.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_overlong_sequence_6_bytes.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_overlong_sequence_6_bytes.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-exponent.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-exponent.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_string_invalid_utf8_after_escape.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_string_invalid_utf8_after_escape.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_lone_utf8_continuation_byte.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_lone_utf8_continuation_byte.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-bigger-int.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_number_invalid-utf-8-in-bigger-int.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_string_overlong_sequence_6_bytes_null.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/i_string_overlong_sequence_6_bytes_null.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_number_real_with_invalid_utf8_after_e.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_number_real_with_invalid_utf8_after_e.json -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/n_object_lone_continuation_byte_in_key_and_trailing_comma.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/nim-json-serialization/HEAD/tests/test_vectors/test_parsing/n_object_lone_continuation_byte_in_key_and_trailing_comma.json -------------------------------------------------------------------------------- /docs/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | - [Introduction](./introduction.md) 2 | 3 | # User guide 4 | 5 | - [Getting started](./getting_started.md) 6 | - [Streaming](./streaming.md) 7 | - [Reference](./reference.md) 8 | 9 | # Developer guide 10 | 11 | - [Updating this book](./book.md) 12 | -------------------------------------------------------------------------------- /tests/nim.cfg: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | --threads:on 11 | 12 | -------------------------------------------------------------------------------- /docs/examples/streamwrite0.nim: -------------------------------------------------------------------------------- 1 | import json_serialization, faststreams/outputs 2 | 3 | let file = fileOutput("output.json") 4 | var writer = JsonWriter[DefaultFlavor].init(file, pretty = true) 5 | 6 | writer.beginArray() 7 | 8 | for i in 0 ..< 2: 9 | writer.beginObject() 10 | 11 | writer.writeMember("id", i) 12 | writer.writeMember("name", "item" & $i) 13 | 14 | writer.endObject() 15 | 16 | writer.endArray() 17 | 18 | file.close() 19 | -------------------------------------------------------------------------------- /docs/src/introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | {{#include ../../README.md:Features}} 4 | 5 | ## Installation 6 | 7 | As a `nimble` dependency: 8 | 9 | ```nim 10 | requires "json_serialization" 11 | ``` 12 | 13 | Via `nimble install`: 14 | 15 | ```text 16 | nimble install json_serialization 17 | ``` 18 | 19 | ## API documentation 20 | 21 | This guide covers basic usage of `json_serialization` - for details, see the 22 | [API reference](./api/). 23 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build: 11 | uses: status-im/nimbus-common-workflow/.github/workflows/common.yml@main 12 | with: 13 | nimble-version: b920dad9ed76c6619be3ec0cfbf0dde6f9e39092 14 | test-command: | 15 | env NIMLANG=c nimble test 16 | env NIMLANG=cpp nimble test 17 | 18 | env nimble examples 19 | -------------------------------------------------------------------------------- /docs/src/book.md: -------------------------------------------------------------------------------- 1 | # Updating this book 2 | 3 | This book is built using [mdBook](https://rust-lang.github.io/mdBook/), which in 4 | turn requires a recent version of `rust` and `cargo` installed. 5 | 6 | ```sh 7 | # Install correct versions of tooling 8 | nimble mdbook 9 | 10 | # Run a local mdbook server 11 | mdbook serve docs 12 | ``` 13 | 14 | A [CI job](../../.github/workflows/docs.yml) automatically published the book 15 | to [GitHub Pages](https://pages.github.com/). 16 | -------------------------------------------------------------------------------- /json_serialization/reader.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | 11 | import 12 | reader_desc, reader_impl, parser 13 | 14 | export 15 | reader_desc, reader_impl, parser 16 | -------------------------------------------------------------------------------- /json_serialization.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | serialization, json_serialization/[format, reader, writer] 12 | 13 | export 14 | serialization, format, reader, writer 15 | -------------------------------------------------------------------------------- /json_serialization/stew/results.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.deprecated: "json_serialization/pkg/results".} 11 | 12 | import json_serialization/pkg/results 13 | export results 14 | -------------------------------------------------------------------------------- /docs/examples/streamwrite1.nim: -------------------------------------------------------------------------------- 1 | import json_serialization, faststreams/outputs 2 | 3 | let file = fileOutput("output.json") 4 | var writer = JsonWriter[DefaultFlavor].init(file) 5 | 6 | # ANCHOR: Nesting 7 | writer.writeObject: 8 | writer.writeMember("status", "ok") 9 | writer.writeName("data") 10 | writer.writeArray: 11 | for i in 0 ..< 2: 12 | writer.writeObject: 13 | writer.writeMember("id", i) 14 | writer.writeMember("name", "item" & $i) 15 | # ANCHOR_END: Nesting 16 | 17 | file.close() 18 | -------------------------------------------------------------------------------- /tests/test_all.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2024 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {. warning[UnusedImport]:off .} 11 | 12 | import 13 | test_lexer, 14 | test_serialization, 15 | test_json_flavor, 16 | test_spec, 17 | test_parser, 18 | test_line_col, 19 | test_reader, 20 | test_writer, 21 | test_valueref 22 | -------------------------------------------------------------------------------- /docs/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Jacek Sieka"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "json_serialization" 7 | 8 | [preprocessor.toc] 9 | command = "mdbook-toc" 10 | renderer = ["html"] 11 | max-level = 3 12 | 13 | [preprocessor.open-on-gh] 14 | command = "mdbook-open-on-gh" 15 | renderer = ["html"] 16 | 17 | [preprocessor.admonish] 18 | command = "mdbook-admonish" 19 | assets_version = "3.1.0" # do not edit: managed by `mdbook-admonish install` 20 | 21 | [output.html] 22 | git-repository-url = "https://github.com/status-im/nim-json-serialization/" 23 | git-branch = "master" 24 | additional-css = ["open-in.css", "./mdbook-admonish.css"] 25 | -------------------------------------------------------------------------------- /fuzzer/fuzz_lexer.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | testutils/fuzzing, 12 | faststreams, 13 | ../json_serialization/lexer 14 | 15 | template prepareLexer(T: type, payload: untyped) = 16 | var stream = unsafeMemoryInput(payload) 17 | var lex = init(JsonLexer, stream) 18 | var value: JsonValueRef[T] 19 | lex.scanValue(value) 20 | 21 | test: 22 | prepareLexer(string, payload) 23 | prepareLexer(uint64, payload) 24 | -------------------------------------------------------------------------------- /json_serialization/std/uri.nim: -------------------------------------------------------------------------------- 1 | # json_serialization 2 | # Copyright (c) 2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import ../../json_serialization, std/uri 13 | export uri 14 | 15 | proc writeValue*(w: var JsonWriter, value: Uri) {.raises: [IOError].} = 16 | w.writeValue($value) 17 | 18 | proc readValue*( 19 | r: var JsonReader, value: var Uri 20 | ) {.raises: [IOError, SerializationError].} = 21 | let s = r.readValue(string) 22 | try: 23 | value = parseUri(s) 24 | except ValueError as exc: 25 | r.raiseUnexpectedValue(exc.msg) 26 | 27 | {.pop.} 28 | -------------------------------------------------------------------------------- /fuzzer/fuzz_parser.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | testutils/fuzzing, 12 | faststreams, 13 | ../json_serialization/parser 14 | 15 | func toReader(input: openArray[byte]): JsonReader[DefaultFlavor] = 16 | var stream = unsafeMemoryInput(input) 17 | JsonReader[DefaultFlavor].init(stream) 18 | 19 | proc executeParser(payload: openArray[byte]) = 20 | try: 21 | var r = toReader(payload) 22 | let z = r.parseValue(uint64) 23 | discard z 24 | except JsonReaderError: 25 | discard 26 | 27 | test: 28 | executeParser(payload) 29 | -------------------------------------------------------------------------------- /json_serialization/std/sets.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import stew/shims/sets, ../../json_serialization/[reader, writer, lexer] 13 | export sets 14 | 15 | type SetType = OrderedSet | HashSet | set 16 | 17 | proc writeValue*(w: var JsonWriter, value: SetType) {.raises: [IOError].} = 18 | w.writeIterable value 19 | 20 | proc readValue*( 21 | r: var JsonReader, value: var SetType 22 | ) {.raises: [IOError, SerializationError].} = 23 | type ElemType = type(value.items) 24 | value = init SetType 25 | for elem in r.readArray(ElemType): 26 | value.incl elem 27 | -------------------------------------------------------------------------------- /docs/examples/getstarted1.nim: -------------------------------------------------------------------------------- 1 | {.push gcsafe, raises: [].} 2 | 3 | import json_serialization 4 | 5 | # ANCHOR: Custom 6 | type JsonRpcId = distinct JsonString 7 | 8 | proc readValue*( 9 | r: var JsonReader, value: var JsonRpcId 10 | ) {.raises: [IOError, JsonReaderError].} = 11 | let tok = r.tokKind 12 | case tok 13 | of JsonValueKind.Number, JsonValueKind.String, JsonValueKind.Null: 14 | # Keep the original value without further processing 15 | value = JsonRpcId(r.parseAsString()) 16 | else: 17 | r.raiseUnexpectedValue("Invalid RequestId, got " & $tok) 18 | 19 | proc writeValue*(w: var JsonWriter, value: JsonRpcId) {.raises: [IOError].} = 20 | w.writeValue(JsonString(value)) # Preserve the original content 21 | 22 | # ANCHOR_END: Custom 23 | 24 | type Request = object 25 | jsonrpc: string 26 | `method`: string 27 | params: seq[int] 28 | id: JsonRpcId 29 | 30 | echo Json.encode(Json.decode("""{"id": "test"}""", Request)) 31 | -------------------------------------------------------------------------------- /tests/test_vectors/test_parsing/i_structure_500_nested_arrays.json: -------------------------------------------------------------------------------- 1 | [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] -------------------------------------------------------------------------------- /fuzzer/readme.md: -------------------------------------------------------------------------------- 1 | ## Fuzz test manual 2 | 3 | You need to install [testutils](https://github.com/status-im/nim-testutils) and 4 | [chronicles](https://github.com/status-im/nim-chronicles). 5 | Then read documentation over there to prepare your execution environment. 6 | 7 | ### Compatibility 8 | 9 | These fuzzers can be compiled with Nim v1.6.16 or newer. 10 | 11 | ### Available fuzz test 12 | 13 | * fuzz_lexer 14 | * fuzz_parser 15 | 16 | ### Manually with libFuzzer/llvmFuzer 17 | #### Compiling 18 | ```sh 19 | nim c -d:llvmFuzzer -d:release -d:chronicles_log_level=FATAL --noMain --cc=clang --passC="-fsanitize=fuzzer" --passL="-fsanitize=fuzzer" fuzzer/fuzz_lexer 20 | ``` 21 | 22 | #### Starting the Fuzzer 23 | Starting the fuzzer is as simple as running the compiled program: 24 | ```sh 25 | ./fuzz_lexer corpus_dir -runs=1000000 26 | ``` 27 | 28 | To see the available options: 29 | ```sh 30 | ./fuzz_lexer test=1 31 | ``` 32 | 33 | You can also use the application to verify a specific test case: 34 | ```sh 35 | ./fuzz_lexer input_file 36 | ``` 37 | -------------------------------------------------------------------------------- /json_serialization/pkg/chronos.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import ../../json_serialization/[reader, writer], ../std/net 13 | 14 | from chronos/transports/common import 15 | TransportAddress, TransportAddressError, initTAddress, `$` 16 | 17 | export TransportAddress, net 18 | 19 | proc writeValue*(w: var JsonWriter, value: TransportAddress) {.raises: [IOError].} = 20 | w.writeValue($value) 21 | 22 | proc readValue*( 23 | r: var JsonReader, value: var TransportAddress 24 | ) {.raises: [IOError, SerializationError].} = 25 | let s = r.readValue(string) 26 | try: 27 | value = initTAddress(s) 28 | except TransportAddressError as exc: 29 | r.raiseUnexpectedValue("Cannot parse TransportAddress: " & exc.msg) 30 | -------------------------------------------------------------------------------- /json_serialization/std/net.nim: -------------------------------------------------------------------------------- 1 | # json_serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import ../../json_serialization, std/net 13 | export net 14 | 15 | when compiles((; import chronos/transports/common)): 16 | # Backwards-compat with json_ser <= 0.4.2 17 | import ../pkg/chronos as jschronos 18 | export jschronos 19 | 20 | proc writeValue*(w: var JsonWriter, value: IpAddress) {.raises: [IOError].} = 21 | w.writeValue($value) 22 | 23 | proc readValue*( 24 | r: var JsonReader, value: var IpAddress 25 | ) {.raises: [IOError, SerializationError].} = 26 | let s = r.readValue(string) 27 | try: 28 | value = parseIpAddress(s) 29 | except ValueError as exc: 30 | r.raiseUnexpectedValue(exc.msg) 31 | 32 | Port.serializesAsBase(Json) 33 | 34 | {.pop.} 35 | -------------------------------------------------------------------------------- /json_serialization/std/options.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import std/options, ../../json_serialization/[reader, writer, lexer] 13 | export options 14 | 15 | template shouldWriteObjectField*(field: Option): bool = 16 | field.isSome 17 | 18 | proc writeValue*(w: var JsonWriter, value: Option) {.raises: [IOError].} = 19 | mixin writeValue 20 | 21 | if value.isSome: 22 | w.writeValue value.get 23 | else: 24 | w.writeValue JsonString("null") 25 | 26 | proc readValue*[T]( 27 | r: var JsonReader, value: var Option[T] 28 | ) {.raises: [IOError, SerializationError].} = 29 | mixin readValue 30 | 31 | if r.tokKind == JsonValueKind.Null: 32 | reset value 33 | r.parseNull() 34 | else: 35 | value = some r.readValue(T) 36 | -------------------------------------------------------------------------------- /tests/test_vectors/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Nicolas Seriot 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Status Research & Development GmbH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /json_serialization/pkg/results.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import pkg/results, ../../json_serialization/[reader, writer, lexer] 13 | 14 | export results 15 | 16 | template shouldWriteObjectField*[T](field: Opt[T]): bool = 17 | field.isOk 18 | 19 | proc writeValue*[T](w: var JsonWriter, value: Opt[T]) {.raises: [IOError].} = 20 | mixin writeValue 21 | 22 | if value.isOk: 23 | w.writeValue(value.get) 24 | else: 25 | w.writeValue JsonString("null") 26 | 27 | proc readValue*[T]( 28 | r: var JsonReader, value: var Opt[T] 29 | ) {.raises: [IOError, SerializationError].} = 30 | mixin readValue 31 | 32 | if r.tokKind == JsonValueKind.Null: 33 | reset value 34 | r.parseNull() 35 | else: 36 | value.ok r.readValue(T) 37 | 38 | func isFieldExpected*[T](_: type[Opt[T]]): bool {.compileTime.} = 39 | false 40 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: Docgen 2 | on: 3 | push: 4 | branches: 5 | - master 6 | - docs 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build: 11 | timeout-minutes: 20 12 | 13 | name: 'Generate & upload documentation' 14 | runs-on: 'ubuntu-latest' 15 | continue-on-error: true 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v4 19 | with: 20 | submodules: true 21 | - uses: actions/cache@v4 22 | with: 23 | path: | 24 | ~/.cargo/bin/ 25 | ~/.cargo/registry/index/ 26 | ~/.cargo/registry/cache/ 27 | ~/.cargo/git/db/ 28 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/*.nimble') }} 29 | - uses: jiro4989/setup-nim-action@v1 30 | with: 31 | nim-version: '2.2.4' 32 | 33 | - name: Generate doc 34 | run: | 35 | nim --version 36 | nimble --version 37 | nimble mdbook 38 | nimble docs || true 39 | 40 | - name: Deploy 41 | uses: peaceiris/actions-gh-pages@v3 42 | with: 43 | github_token: ${{ secrets.GITHUB_TOKEN }} 44 | publish_dir: ./docs/book 45 | force_orphan: true 46 | -------------------------------------------------------------------------------- /docs/examples/getstarted0.nim: -------------------------------------------------------------------------------- 1 | # ANCHOR: Import 2 | {.push gcsafe, raises: [].} # Encourage exception handling hygiene in procedures! 3 | 4 | import json_serialization 5 | export json_serialization 6 | # ANCHOR_END: Import 7 | 8 | # ANCHOR: Request 9 | type Request = object 10 | jsonrpc: string 11 | `method`: string # Quote Nim keywords 12 | params: seq[int] # Map JSON array to `seq` 13 | id: int 14 | 15 | # ANCHOR_END: Request 16 | 17 | # ANCHOR: Decode 18 | # Decode the string into our Request type 19 | let decoded = Json.decode( 20 | """{"jsonrpc": "2.0", "method": "subtract", "params": [42, 3], "id": 1}""", Request 21 | ) 22 | 23 | echo decoded.id 24 | # ANCHOR_END: Decode 25 | 26 | # ANCHOR: Pretty 27 | # Now that we have a `Request` instance, we can pretty-print it: 28 | echo Json.encode(decoded, pretty = true) 29 | # ANCHOR_END: Pretty 30 | 31 | # ANCHOR: Errors 32 | try: 33 | # Oops, a string was used for the `id` field! 34 | discard Json.decode("""{"id": "test"}""", Request) 35 | except JsonError as exc: 36 | # "" helps identify the source of the document - this can be a 37 | # filename, URL or something else that helps the user find the error 38 | echo "Failed to parse document: ", exc.formatMsg("") 39 | # ANCHOR_END: Errors 40 | -------------------------------------------------------------------------------- /json_serialization/std/tables.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import std/strutils, stew/shims/tables, ../../json_serialization/[reader, writer, lexer] 13 | 14 | export tables 15 | 16 | type TableType = OrderedTable | Table 17 | 18 | proc writeValue*(w: var JsonWriter, value: TableType) {.raises: [IOError].} = 19 | w.writeObject: 20 | for key, val in value: 21 | w.writeField $key, val 22 | 23 | template to*(a: string, b: typed): untyped = 24 | {.error: "doesnt support keys with type " & $type(b).} 25 | 26 | template to*(a: string, b: type int): int = 27 | parseInt(a) 28 | 29 | template to*(a: string, b: type float): float = 30 | parseFloat(a) 31 | 32 | template to*(a: string, b: type string): string = 33 | a 34 | 35 | proc readValue*( 36 | r: var JsonReader, value: var TableType 37 | ) {.raises: [IOError, SerializationError].} = 38 | try: 39 | type KeyType = type(value.keys) 40 | type ValueType = type(value.values) 41 | value = init TableType 42 | for key, val in r.readObject(string, ValueType): 43 | value[to(key, KeyType)] = val 44 | except ValueError as ex: 45 | r.raiseUnexpectedValue("TableType: " & ex.msg) 46 | -------------------------------------------------------------------------------- /config.nims: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | if defined(windows): 11 | # disable timestamps in Windows PE headers - https://wiki.debian.org/ReproducibleBuilds/TimestampsInPEBinaries 12 | switch("passL", "-Wl,--no-insert-timestamp") 13 | # increase stack size, unless something else is setting the stack size 14 | if not defined(windowsNoSetStack): 15 | switch("passL", "-Wl,--stack,8388608") 16 | # https://github.com/nim-lang/Nim/issues/4057 17 | --tlsEmulation:off 18 | if defined(i386): 19 | # set the IMAGE_FILE_LARGE_ADDRESS_AWARE flag so we can use PAE, if enabled, and access more than 2 GiB of RAM 20 | switch("passL", "-Wl,--large-address-aware") 21 | 22 | # Avoid some rare stack corruption while using exceptions with a SEH-enabled 23 | # toolchain: https://github.com/status-im/nimbus-eth2/issues/3121 24 | switch("define", "nimRawSetjmp") 25 | 26 | # begin Nimble config (version 1) 27 | when defined(windows): 28 | when fileExists("nimble-win.paths"): 29 | include "nimble-win.paths" 30 | elif fileExists("nimble.paths"): 31 | include "nimble.paths" 32 | elif defined(linux): 33 | when fileExists("nimble-win.paths"): 34 | include "nimble-linux.paths" 35 | elif fileExists("nimble.paths"): 36 | include "nimble.paths" 37 | # end Nimble config 38 | -------------------------------------------------------------------------------- /docs/src/streaming.md: -------------------------------------------------------------------------------- 1 | # Streaming 2 | 3 | `JsonWriter` can be used to incrementally write JSON data. 4 | 5 | Incremental processing is ideal for large documents or when you want to avoid building the entire JSON structure in memory. 6 | 7 | 8 | 9 | ## Writing 10 | 11 | You can use `JsonWriter` to write JSON objects, arrays, and values step by step, directly to a file or any output stream. 12 | 13 | The process is similar to when you override `writeValue` to provide custom serialization. 14 | 15 | ### Example: Writing a JSON Array of Objects 16 | 17 | Suppose you want to write a large array of objects to a file, one at a time: 18 | 19 | ```nim 20 | {{#include ../examples/streamwrite0.nim}} 21 | ``` 22 | 23 | Resulting file (`output.json`): 24 | ```json 25 | [ 26 | { 27 | "id": 0, 28 | "name": "item0" 29 | }, 30 | { 31 | "id": 1, 32 | "name": "item1" 33 | } 34 | ] 35 | ``` 36 | 37 | ### Example: Writing Nested Structures 38 | 39 | Objects and arrays can be nested arbitrarily. 40 | 41 | Here is the same array of JSON objects, nested in an envelope containing an additional `status` field. 42 | 43 | Instead of manually placing `begin`/`end` pairs, we're using the convenience helpers `writeObject` and `writeArrayMember`, along with `writeElement` to manage the required element markers: 44 | 45 | ```ni 46 | {{#include ../examples/streamwrite1.nim:Nesting}} 47 | ``` 48 | 49 | This produces a the following output - notice the more compact representation when `pretty = true` is not used: 50 | ```json 51 | {"status":"ok","data":[{"id":0,"name":"item0"},{"id":1,"name":"item1"}]} 52 | ``` 53 | -------------------------------------------------------------------------------- /tests/utils.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | strutils, os 12 | 13 | # `dedent` exists in newer Nim version and doesn't behave the same 14 | func test_dedent*(s: string): string = 15 | var 16 | s = s.strip(leading = false) 17 | minIndent = high(int) 18 | for l in s.splitLines: 19 | let indent = count(l, ' ') 20 | if indent == 0: continue 21 | if indent < minIndent: minIndent = indent 22 | s.unindent(minIndent) 23 | 24 | proc pathRelativeTo*(fileName, base: string): string = 25 | try: 26 | relativePath(fileName, base) 27 | except Exception as err: 28 | raise newException(Defect, err.msg) 29 | 30 | const 31 | parsingPath* = "tests/test_vectors/test_parsing" 32 | transformPath* = "tests/test_vectors/test_transform" 33 | 34 | const 35 | allowedToFail* = [ 36 | "string_1_escaped_invalid_codepoint.json", 37 | "string_3_escaped_invalid_codepoints.json", 38 | "i_number_huge_exp.json", 39 | "i_string_1st_surrogate_but_2nd_missing.json", 40 | "i_string_incomplete_surrogate_and_escape_valid.json", 41 | "i_string_invalid_lonely_surrogate.json", 42 | "i_string_invalid_surrogate.json", 43 | "i_string_inverted_surrogates_U+1D11E.json", 44 | "i_string_UTF-16LE_with_BOM.json", 45 | "i_string_utf16BE_no_BOM.json", 46 | "i_string_utf16LE_no_BOM.json", 47 | "i_structure_UTF-8_BOM_empty_object.json", 48 | ] 49 | -------------------------------------------------------------------------------- /tests/test_vectors/README.md: -------------------------------------------------------------------------------- 1 | # JSON Parsing Test Suite 2 | A comprehensive test suite for RFC 8259 compliant JSON parsers 3 | 4 | This repository was created as an appendix to the article [Parsing JSON is a Minefield 💣](http://seriot.ch/parsing_json.php). 5 | 6 | **/parsers/** 7 | 8 | This directory contains several parsers and tiny wrappers to turn the parsers into JSON validators, by returning a specific value. 9 | 10 | - `0` the parser did accept the content 11 | - `1` the parser did reject the content 12 | - `>1` the process did crash 13 | - `timeout` happens after 5 seconds 14 | 15 | **/test\_parsing/** 16 | 17 | The name of these files tell if their contents should be accepted or rejected. 18 | 19 | - `y_` content must be accepted by parsers 20 | - `n_` content must be rejected by parsers 21 | - `i_` parsers are free to accept or reject content 22 | 23 | **/test\_transform/** 24 | 25 | These files contain weird structures and characters that parsers may understand differently, eg: 26 | 27 | - huge numbers 28 | - dictionaries with similar keys 29 | - NULL characters 30 | - escaped invalid strings 31 | 32 | These files were used to produce `results/transform.html`. 33 | 34 | **/run_tests.py** 35 | 36 | Run all parsers with all files: 37 | 38 | $ python3 run_tests.py 39 | 40 | Run all parsers with a specific file: 41 | 42 | $ python3 run_tests.py file.json 43 | 44 | Run specific parsers with all files: 45 | 46 | $ echo '["Python 2.7.10", "Python 3.5.2"]' > python_only.json 47 | $ python3 run_tests.py --filter=python_only.json 48 | 49 | The script writes logs in `results/logs.txt`. 50 | 51 | The script then reads `logs.txt` and generates `results/parsing.html`. 52 | 53 | **/results/** 54 | 55 | JSON Parsing Tests 56 | -------------------------------------------------------------------------------- /docs/examples/getstarted2.nim: -------------------------------------------------------------------------------- 1 | {.push gcsafe, raises: [].} 2 | 3 | # ANCHOR: Import 4 | import json_serialization, json_serialization/pkg/results 5 | export json_serialization, results 6 | # ANCHOR_END: Import 7 | 8 | # ANCHOR: Create 9 | createJsonFlavor JrpcSys, 10 | automaticObjectSerialization = false, 11 | requireAllFields = true, 12 | omitOptionalFields = true, # Don't output `none` values when writing 13 | allowUnknownFields = false 14 | # ANCHOR_END: Create 15 | 16 | # ANCHOR: Custom 17 | type JsonRpcId = distinct JsonString 18 | 19 | proc readValue*( 20 | r: var JsonReader[JrpcSys], value: var JsonRpcId 21 | ) {.raises: [IOError, JsonReaderError].} = 22 | let tok = r.tokKind 23 | case tok 24 | of JsonValueKind.Number, JsonValueKind.String, JsonValueKind.Null: 25 | # Keep the original value without further processing 26 | value = JsonRpcId(r.parseAsString()) 27 | else: 28 | r.raiseUnexpectedValue("Invalid RequestId, got " & $tok) 29 | 30 | proc writeValue*(w: var JsonWriter[JrpcSys], value: JsonRpcId) {.raises: [IOError].} = 31 | w.writeValue(JsonString(value)) # Preserve the original content 32 | # ANCHOR_END: Custom 33 | 34 | # ANCHOR: Request 35 | type Request = object 36 | jsonrpc: string 37 | `method`: string 38 | params: Opt[seq[int]] 39 | id: Opt[JsonRpcId] 40 | # ANCHOR_END: Request 41 | 42 | # ANCHOR: Auto 43 | # Allow serializing the `Request` type - serializing other types will result in 44 | # a compile-time error because `automaticObjectSerialization` is false! 45 | JrpcSys.useDefaultSerializationFor Request 46 | # ANCHOR_END: Auto 47 | 48 | # ANCHOR: Encode 49 | const json = """{"jsonrpc": "2.0", "method": "subtract", "params": [42, 3], "id": 1}""" 50 | 51 | echo JrpcSys.encode(JrpcSys.decode(json, Request)) 52 | # ANCHOR_END: Encode 53 | -------------------------------------------------------------------------------- /docs/examples/reference0.nim: -------------------------------------------------------------------------------- 1 | import std/json, json_serialization 2 | 3 | # ANCHOR: Decode 4 | const rawJson = """{"name": "localhost", "port": 42}""" 5 | type 6 | NimServer = object 7 | name: string 8 | port: int 9 | 10 | MixedServer = object 11 | name: JsonValueRef[uint64] 12 | port: int 13 | 14 | StringServer = object 15 | name: JsonString 16 | port: JsonString 17 | 18 | var conf = defaultJsonReaderConf 19 | conf.nestedDepthLimit = 0 20 | 21 | # decode into native Nim 22 | let native = Json.decode(rawJson, NimServer) 23 | 24 | # decode into mixed Nim + JsonValueRef 25 | let mixed = Json.decode(rawJson, MixedServer) 26 | 27 | # decode any value into nested json string 28 | let str = Json.decode(rawJson, StringServer) 29 | 30 | # decode any valid JSON, using the `json_serialization` node type 31 | let value = Json.decode(rawJson, JsonValueRef[uint64]) 32 | 33 | # decode any valid JSON, using the `std/json` node type 34 | let stdjson = Json.decode(rawJson, JsonNode) 35 | 36 | # read JSON document from file instead 37 | let file = Json.loadFile("filename.json", NimServer) 38 | # ANCHOR_END: Decode 39 | 40 | # ANCHOR: Reader 41 | var reader = JsonReader[DefaultFlavor].init(memoryInput(rawJson)) 42 | let native2 = reader.readValue(NimServer) 43 | 44 | # Overwrite an existing instance 45 | var reader2 = JsonReader[DefaultFlavor].init(memoryInput(rawJson)) 46 | var native3: NimServer 47 | reader2.readValue(native3) 48 | # ANCHOR_END: Reader 49 | 50 | # ANCHOR: Encode 51 | # Convert object to string 52 | echo Json.encode(native) 53 | 54 | # Write JSON to file 55 | Json.saveFile("filename.json", native) 56 | 57 | # Pretty-print a tuple 58 | echo Json.encode((x: 4, y: 5), pretty = true) 59 | # ANCHOR_END: Encode 60 | 61 | # ANCHOR: Writer 62 | var output = memoryOutput() 63 | var writer = JsonWriter[DefaultFlavor].init(output) 64 | writer.writeValue(native) 65 | echo output.getOutput(string) 66 | # ANCHOR_END: Writer 67 | -------------------------------------------------------------------------------- /json_serialization.nimble: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023-2024 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | mode = ScriptMode.Verbose 11 | 12 | packageName = "json_serialization" 13 | version = "0.4.4" 14 | author = "Status Research & Development GmbH" 15 | description = "Flexible JSON serialization not relying on run-time type information" 16 | license = "Apache License 2.0" 17 | skipDirs = @["tests", "fuzzer"] 18 | 19 | requires "nim >= 1.6.0", 20 | "faststreams >= 0.5.0", 21 | "serialization", 22 | "stew >= 0.2.0", 23 | "results" 24 | 25 | let nimc = getEnv("NIMC", "nim") # Which nim compiler to use 26 | let lang = getEnv("NIMLANG", "c") # Which backend (c/cpp/js) 27 | let flags = getEnv("NIMFLAGS", "") # Extra flags for the compiler 28 | let verbose = getEnv("V", "") notin ["", "0"] 29 | 30 | from os import quoteShell 31 | from strutils import endsWith 32 | 33 | let cfg = 34 | " --styleCheck:usages --styleCheck:error" & 35 | (if verbose: "" else: " --verbosity:0 --hints:off") & 36 | " --outdir:build " & 37 | quoteShell("--nimcache:build/nimcache/$projectName") & 38 | " -d:nimOldCaseObjects -d:serializationTestAllRountrips" & 39 | (if NimMajor >= 2: " -d:unittest2Static" else: "") 40 | 41 | proc build(args, path: string) = 42 | exec nimc & " " & lang & " " & cfg & " " & flags & " " & args & " " & path 43 | 44 | proc run(args, path: string) = 45 | build args & " --mm:refc -r", path 46 | if (NimMajor, NimMinor) > (1, 6): 47 | build args & " --mm:orc -r", path 48 | 49 | task test, "Run all tests": 50 | for threads in ["--threads:off", "--threads:on"]: 51 | run threads, "tests/test_all" 52 | 53 | task examples, "Build examples": 54 | # Build book examples 55 | for file in listFiles("docs/examples"): 56 | if file.endsWith(".nim"): 57 | build "--threads:on", file 58 | 59 | task mdbook, "Install mdbook (requires cargo)": 60 | exec "cargo install mdbook@0.4.51 mdbook-toc@0.14.2 mdbook-open-on-gh@2.4.3 mdbook-admonish@1.20.0" 61 | 62 | task docs, "Generate API documentation": 63 | exec "mdbook build docs" 64 | exec nimc & " doc " & "--git.url:https://github.com/status-im/nim-json-serialization --git.commit:master --outdir:docs/book/api --project json_serialization" 65 | -------------------------------------------------------------------------------- /tests/test_spec.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | std/[strutils, os], 12 | faststreams, 13 | ./utils 14 | 15 | # we want to test lexer internals 16 | # hence use include instead of import 17 | include 18 | ../json_serialization/lexer 19 | 20 | proc inputFile(fileName: string): InputStream {.raises: [IOError].} = 21 | when nimvm: 22 | let data = staticRead(pathRelativeTo(fileName, "tests")) 23 | unsafeMemoryInput(data) 24 | else: 25 | memFileInput(fileName) 26 | 27 | proc yCase(fileName, name: string): bool {.raises: [IOError].} = 28 | var stream = inputFile(fileName) 29 | var lex = init(JsonLexer, stream) 30 | var value: string 31 | lex.scanValue(value) 32 | if lex.err != errNone: 33 | debugEcho name, " FAIL ", lex.err 34 | debugEcho value 35 | return false 36 | true 37 | 38 | proc nCase(fileName, name: string): bool {.raises: [IOError].} = 39 | var stream = inputFile(fileName) 40 | var lex = init(JsonLexer, stream, {}) 41 | var value: string 42 | lex.scanValue(value) 43 | discard lex.nonws() 44 | if lex.ok and lex.readable: 45 | # contains garbage 46 | return true 47 | if lex.err == errNone: 48 | debugEcho name, " FAIL, should error" 49 | debugEcho value 50 | return false 51 | true 52 | 53 | proc test() {.raises: [OSError, IOError].} = 54 | var checked = 0 55 | for fileName in walkDirRec(parsingPath): 56 | let (_, name) = fileName.splitPath() 57 | if name.startsWith("y_"): 58 | doAssert yCase(fileName, name) 59 | inc checked 60 | elif name.startsWith("n_"): 61 | doAssert nCase(fileName, name) 62 | inc checked 63 | # test cases starts with i_ are allowed to 64 | # fail or success depending on the implementation details 65 | elif name.startsWith("i_"): 66 | if name notin allowedToFail: 67 | doAssert yCase(fileName, name) 68 | inc checked 69 | 70 | for fileName in walkDirRec(transformPath): 71 | let (_, name) = fileName.splitPath() 72 | if name notin allowedToFail: 73 | doAssert yCase(fileName, name) 74 | inc checked 75 | 76 | doAssert checked == 328, $checked 77 | 78 | static: 79 | test() 80 | echo "static ok" 81 | test() 82 | echo "ok" 83 | -------------------------------------------------------------------------------- /tests/test_line_col.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | faststreams, 12 | unittest2 13 | 14 | # we want to test lexer internals 15 | # hence use include instead of import 16 | include 17 | ../json_serialization/lexer 18 | 19 | type 20 | TestCase = object 21 | line: int 22 | col: int 23 | text: string 24 | flags: JsonReaderFlags 25 | conf: JsonReaderConf 26 | 27 | func tc(line: int, col: int, text: string): TestCase = 28 | TestCase( 29 | line: line, 30 | col: col, 31 | text: text, 32 | flags: defaultJsonReaderFlags, 33 | conf: defaultJsonReaderConf, 34 | ) 35 | 36 | func tc(line: int, col: int, text: string, flags: JsonReaderFlags): TestCase = 37 | TestCase( 38 | line: line, 39 | col: col, 40 | text: text, 41 | flags: flags, 42 | conf: defaultJsonReaderConf, 43 | ) 44 | 45 | when false: 46 | func tc(line: int, col: int, text: string, conf: JsonReaderConf): TestCase = 47 | TestCase( 48 | line: line, 49 | col: col, 50 | text: text, 51 | flags: defaultJsonReaderFlags, 52 | conf: conf, 53 | ) 54 | 55 | func noComment(): JsonReaderFlags = 56 | result = defaultJsonReaderFlags 57 | result.excl JsonReaderFlag.allowComments 58 | 59 | func noTrailingComma(): JsonReaderFlags = 60 | result = defaultJsonReaderFlags 61 | result.excl JsonReaderFlag.trailingComma 62 | 63 | const testCases = [ 64 | tc(2, 19, """ 65 | { 66 | "a" : 1234.567 // comments 67 | } 68 | """, noComment()), 69 | 70 | tc(2, 19, """ 71 | { 72 | "a" : 1234.567 /* comments */ 73 | } 74 | """, noComment()), 75 | 76 | tc(4, 3, """ 77 | { 78 | "a" : 1234.567 /* comments 79 | } 80 | """), 81 | 82 | tc(2, 8, """ 83 | { 84 | "a" 1234.567 85 | } 86 | """), 87 | 88 | tc(3, 3, """ 89 | { 90 | 91 | , 92 | 93 | """), 94 | 95 | tc(4, 1, """ 96 | { 97 | "a": 98 | 1 , 99 | } 100 | """, noTrailingComma()), 101 | 102 | tc(3, 4, """ 103 | [ 104 | 105 | , 106 | 107 | """), 108 | 109 | tc(2, 3, """ 110 | [ 111 | b 112 | ] 113 | """), 114 | 115 | tc(4, 1, """ 116 | [ 117 | 1 118 | , 119 | ] 120 | """, noTrailingComma()), 121 | ] 122 | 123 | suite "Test line col": 124 | for i, tc in testCases: 125 | runtimeTest $i: 126 | var stream = unsafeMemoryInput(tc.text) 127 | var lex = init(JsonLexer, stream, tc.flags, tc.conf) 128 | var value: JsonValueRef[uint64] 129 | lex.scanValue(value) 130 | check: 131 | lex.err != errNone 132 | lex.line == tc.line 133 | lex.tokenStartCol == tc.col 134 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nim-json-serialization 2 | 3 | [![License: Apache](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) 5 | ![Stability: experimental](https://img.shields.io/badge/stability-experimental-orange.svg) 6 | ![Github action](https://github.com/status-im/nim-json-serialization/workflows/CI/badge.svg) 7 | 8 | ## Introduction 9 | 10 | 11 | 12 | `nim-json-serialization` is a library in the [nim-serialization](https://github.com/status-im/nim-serialization) family for turning Nim objects into JSON documents and back. Features include: 13 | 14 | - Efficient coding of JSON documents directly to and from Nim data types 15 | - Full type-based customization of both parsing and formatting 16 | - Flavors for defining multiple JSON serialization styles per Nim type 17 | - Efficient skipping of tags and values for partial JSON parsing 18 | - Flexibility in mixing type-based and dynamic JSON access 19 | - Structured `JsonValueRef` node type for DOM-style access to parsed document 20 | - Flat `JsonString` type for passing nested JSON documents between abstraction layers 21 | - Seamless interoperability with [`std/json`](https://nim-lang.org/docs/json.html) and `JsonNode` 22 | - Full [RFC8259 spec compliance](https://datatracker.ietf.org/doc/html/rfc8259) including the notorious JSON number 23 | - Passes [JSONTestSuite](https://github.com/nst/JSONTestSuite) 24 | - Customizable parser strictness including support for non-standard extensions 25 | - Well-defined handling of malformed / malicious inputs with configurable parsing limits 26 | - Fuzzing and comprehensive manual test coverage 27 | - Since v0.4.4, compile time encode/decode is supported. This means you can initialize a const value using decode. It is also ok to use it inside a static block or other Nim VM code. 28 | 29 | 30 | 31 | ## Getting started 32 | 33 | ```nim 34 | requires "json_serialization" 35 | ``` 36 | 37 | Create a type and use it to encode and decode JSON: 38 | 39 | ```nim 40 | import json_serialization 41 | 42 | type Request = object 43 | jsonrpc: string 44 | `method`: string 45 | 46 | let 47 | json = """{"jsonrpc": "2.0", "method": "name"}""" 48 | decoded = Json.decode(json, Request) 49 | 50 | echo decoded.jsonrpc 51 | echo Json.encode(decoded, pretty=true) 52 | ``` 53 | 54 | ## Documentation 55 | 56 | See the [user guide](https://status-im.github.io/nim-json-serialization/). 57 | 58 | ## Contributing 59 | 60 | Contributions are welcome - please make sure to add test coverage for features and fixes! 61 | 62 | `json_serialization` follows the [Status Nim Style Guide](https://status-im.github.io/nim-style-guide/). 63 | 64 | ## License 65 | 66 | Licensed and distributed under either of 67 | 68 | * MIT license: [LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT 69 | 70 | or 71 | 72 | * Apache License, Version 2.0, ([LICENSE-APACHEv2](LICENSE-APACHEv2) or http://www.apache.org/licenses/LICENSE-2.0) 73 | 74 | at your option. These files may not be copied, modified, or distributed except according to those terms. 75 | -------------------------------------------------------------------------------- /tests/test_valueref.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2024 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | unittest2, 12 | ../json_serialization, 13 | ../json_serialization/value_ops 14 | 15 | func jsonBool(x: bool): JsonValueRef[uint64] = 16 | JsonValueRef[uint64](kind: JsonValueKind.Bool, boolVal: x) 17 | 18 | func jsonNull(): JsonValueRef[uint64] = 19 | JsonValueRef[uint64](kind: JsonValueKind.Null) 20 | 21 | template valueRefVars() {.dirty.} = 22 | let objA = JsonValueRef[uint64]( 23 | kind: JsonValueKind.Object, 24 | objVal: [ 25 | ("a", jsonBool(true)), 26 | ].toOrderedTable 27 | ) 28 | 29 | let objA2 = JsonValueRef[uint64]( 30 | kind: JsonValueKind.Object, 31 | objVal: [ 32 | ("a", jsonBool(true)), 33 | ].toOrderedTable 34 | ) 35 | 36 | let objABNull = JsonValueRef[uint64]( 37 | kind: JsonValueKind.Object, 38 | objVal: [ 39 | ("a", jsonBool(true)), 40 | ("b", jsonNull()) 41 | ].toOrderedTable 42 | ) 43 | 44 | let objAB = JsonValueRef[uint64]( 45 | kind: JsonValueKind.Object, 46 | objVal: [ 47 | ("a", jsonBool(true)), 48 | ("b", jsonBool(true)) 49 | ].toOrderedTable 50 | ) 51 | 52 | let objInArrayA = JsonValueRef[uint64]( 53 | kind: JsonValueKind.Array, 54 | arrayVal: @[ 55 | objA 56 | ] 57 | ) 58 | 59 | let objInArrayA2 = JsonValueRef[uint64]( 60 | kind: JsonValueKind.Array, 61 | arrayVal: @[ 62 | objA2 63 | ] 64 | ) 65 | 66 | let objInArrayAB = JsonValueRef[uint64]( 67 | kind: JsonValueKind.Array, 68 | arrayVal: @[ 69 | objAB 70 | ] 71 | ) 72 | 73 | let objInArrayABNull = JsonValueRef[uint64]( 74 | kind: JsonValueKind.Array, 75 | arrayVal: @[ 76 | objABNull 77 | ] 78 | ) 79 | 80 | let objInObjA = JsonValueRef[uint64]( 81 | kind: JsonValueKind.Object, 82 | objVal: [ 83 | ("x", objA) 84 | ].toOrderedTable 85 | ) 86 | 87 | let objInObjA2 = JsonValueRef[uint64]( 88 | kind: JsonValueKind.Object, 89 | objVal: [ 90 | ("x", objA2) 91 | ].toOrderedTable 92 | ) 93 | 94 | let objInObjAB = JsonValueRef[uint64]( 95 | kind: JsonValueKind.Object, 96 | objVal: [ 97 | ("x", objAB) 98 | ].toOrderedTable 99 | ) 100 | 101 | let objInObjABNull = JsonValueRef[uint64]( 102 | kind: JsonValueKind.Object, 103 | objVal: [ 104 | ("x", objABNull) 105 | ].toOrderedTable 106 | ) 107 | 108 | suite "Test JsonValueRef": 109 | test "Test table keys equality": 110 | valueRefVars() 111 | check objA != objAB 112 | check objA == objA2 113 | check objA != objABNull 114 | check objAB != objABNull 115 | 116 | check objInArrayA != objInArrayAB 117 | check objInArrayA != objInArrayABNull 118 | check objInArrayA == objInArrayA2 119 | check objInArrayAB != objInArrayABNull 120 | 121 | check objInObjA != objInObjAB 122 | check objInObjA != objInObjABNull 123 | check objInObjA == objInObjA2 124 | check objInObjAB != objInObjABNull 125 | 126 | test "Test compare": 127 | valueRefVars() 128 | check compare(objA, objAB) == false 129 | check compare(objA, objA2) == true 130 | check compare(objA, objABNull) == true 131 | check compare(objAB, objABNull) == false 132 | 133 | check compare(objInArrayA, objInArrayAB) == false 134 | check compare(objInArrayA, objInArrayABNull) == true 135 | check compare(objInArrayA, objInArrayA2) == true 136 | check compare(objInArrayAB, objInArrayABNull) == false 137 | 138 | check compare(objInObjA, objInObjAB) == false 139 | check compare(objInObjA, objInObjABNull) == true 140 | check compare(objInObjA, objInObjA2) == true 141 | check compare(objInObjAB, objInObjABNull) == false 142 | -------------------------------------------------------------------------------- /json_serialization/types.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import 13 | std/tables, 14 | serialization/errors 15 | 16 | export 17 | tables, 18 | errors 19 | 20 | type 21 | JsonError* = object of SerializationError 22 | 23 | JsonString* = distinct string 24 | ## A string containing valid JSON. 25 | ## Used to preserve and pass on parts of a JSON document to another parser 26 | ## or layer without interpreting it further 27 | 28 | JsonVoid* = object 29 | ## Marker used for skipping a JSON value during parsing 30 | 31 | JsonSign* {.pure.} = enum 32 | None 33 | Pos 34 | Neg 35 | 36 | # This is a special type to parse complete 37 | # json number. 38 | JsonNumber*[T: string or uint64] = object 39 | sign*: JsonSign 40 | integer*: T 41 | fraction*: string 42 | expSign*: JsonSign 43 | exponent*: T 44 | 45 | JsonReaderFlag* {.pure.} = enum 46 | allowUnknownFields 47 | requireAllFields 48 | escapeHex 49 | relaxedEscape 50 | portableInt 51 | trailingComma # on 52 | allowComments # on 53 | leadingFraction # on 54 | integerPositiveSign # on 55 | 56 | JsonReaderFlags* = set[JsonReaderFlag] 57 | 58 | JsonReaderConf* = object 59 | nestedDepthLimit*: int 60 | arrayElementsLimit*: int 61 | objectMembersLimit*: int 62 | integerDigitsLimit*: int 63 | fractionDigitsLimit*: int 64 | exponentDigitsLimit*: int 65 | stringLengthLimit*: int 66 | 67 | JsonValueKind* {.pure.} = enum 68 | String 69 | Number 70 | Object 71 | Array 72 | Bool 73 | Null 74 | 75 | JsonObjectType*[T: string or uint64] = OrderedTable[string, JsonValueRef[T]] 76 | 77 | JsonValueRef*[T: string or uint64] = ref JsonValue[T] 78 | JsonValue*[T: string or uint64] = object 79 | case kind*: JsonValueKind 80 | of JsonValueKind.String: 81 | strVal*: string 82 | of JsonValueKind.Number: 83 | numVal*: JsonNumber[T] 84 | of JsonValueKind.Object: 85 | objVal*: JsonObjectType[T] 86 | of JsonValueKind.Array: 87 | arrayVal*: seq[JsonValueRef[T]] 88 | of JsonValueKind.Bool: 89 | boolVal*: bool 90 | of JsonValueKind.Null: 91 | discard 92 | 93 | const 94 | minPortableInt* = -9007199254740991 # -2**53 + 1 95 | maxPortableInt* = 9007199254740991 # +2**53 - 1 96 | 97 | defaultJsonReaderFlags* = { 98 | JsonReaderFlag.integerPositiveSign, 99 | JsonReaderFlag.allowComments, 100 | JsonReaderFlag.leadingFraction, 101 | JsonReaderFlag.trailingComma, 102 | } 103 | 104 | defaultJsonReaderConf* = JsonReaderConf( 105 | nestedDepthLimit: 512, 106 | arrayElementsLimit: 0, 107 | objectMembersLimit: 0, 108 | integerDigitsLimit: 128, 109 | fractionDigitsLimit: 128, 110 | exponentDigitsLimit: 32, 111 | stringLengthLimit: 0, 112 | ) 113 | 114 | template `==`*(lhs, rhs: JsonString): bool = 115 | string(lhs) == string(rhs) 116 | 117 | template valueType*[K, V](_: type OrderedTable[K, V]): untyped = V 118 | 119 | func isFloat*(x: JsonNumber): bool = 120 | x.fraction.len > 0 121 | 122 | func hasExponent*[T](x: JsonNumber[T]): bool = 123 | when T is string: 124 | x.exponent.len > 0 125 | else: 126 | x.exponent > 0 127 | 128 | func toInt*(sign: JsonSign): int = 129 | case sign: 130 | of JsonSign.None: 1 131 | of JsonSign.Pos: 0 132 | of JsonSign.Neg: -1 133 | 134 | func `==`*(lhs, rhs: JsonValueRef): bool = 135 | if lhs.isNil and rhs.isNil: 136 | return true 137 | 138 | if not lhs.isNil and rhs.isNil: 139 | return false 140 | 141 | if lhs.isNil and not rhs.isNil: 142 | return false 143 | 144 | if lhs.kind != rhs.kind: 145 | return false 146 | 147 | case lhs.kind 148 | of JsonValueKind.String: 149 | lhs.strVal == rhs.strVal 150 | of JsonValueKind.Number: 151 | lhs.numVal == rhs.numVal 152 | of JsonValueKind.Object: 153 | if lhs.objVal.len != rhs.objVal.len: 154 | return false 155 | for k, v in lhs.objVal: 156 | let rhsVal = rhs.objVal.getOrDefault(k, nil) 157 | if rhsVal.isNil: 158 | return false 159 | if rhsVal != v: 160 | return false 161 | true 162 | of JsonValueKind.Array: 163 | if lhs.arrayVal.len != rhs.arrayVal.len: 164 | return false 165 | for i, x in lhs.arrayVal: 166 | if x != rhs.arrayVal[i]: 167 | return false 168 | true 169 | of JsonValueKind.Bool: 170 | lhs.boolVal == rhs.boolVal 171 | of JsonValueKind.Null: 172 | true 173 | 174 | template `$`*(s: JsonString): string = 175 | string(s) 176 | 177 | {.pop.} 178 | -------------------------------------------------------------------------------- /json_serialization/value_ops.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.push raises: [], gcsafe.} 11 | 12 | import 13 | std/[tables, strutils], 14 | ./types 15 | 16 | proc len*(n: JsonValueRef): int = 17 | ## If `n` is a `JsonValueKind.Array`, it returns the number of elements. 18 | ## If `n` is a `JsonValueKind.Object`, it returns the number of pairs. 19 | ## Else it returns 0. 20 | case n.kind 21 | of JsonValueKind.Array: result = n.arrayVal.len 22 | of JsonValueKind.Object: result = n.objVal.len 23 | else: discard 24 | 25 | proc `[]`*(node: JsonValueRef, name: string): JsonValueRef {.inline.} = 26 | ## Gets a field from a `JsonValueKind.Object`, which must not be nil. 27 | assert(not isNil(node)) 28 | assert(node.kind == JsonValueKind.Object) 29 | node.objVal.getOrDefault(name, nil) 30 | 31 | proc `[]`*(node: JsonValueRef, index: int): JsonValueRef {.inline.} = 32 | ## Gets the node at `index` in an Array. Result is undefined if `index` 33 | ## is out of bounds, but as long as array bound checks are enabled it will 34 | ## result in an exception. 35 | assert(not isNil(node)) 36 | assert(node.kind == JsonValueKind.Array) 37 | node.arrayVal[index] 38 | 39 | proc contains*(node: JsonValueRef, key: string): bool = 40 | ## Checks if `key` exists in `node`. 41 | assert(node.kind == JsonValueKind.Object) 42 | node.objVal.hasKey(key) 43 | 44 | proc contains*(node: JsonValueRef, val: JsonValueRef): bool = 45 | ## Checks if `val` exists in array `node`. 46 | assert(node.kind == JsonValueKind.Array) 47 | find(node.arrayVal, val) >= 0 48 | 49 | proc `[]=`*(obj: JsonValueRef, key: string, val: JsonValueRef) {.inline.} = 50 | ## Sets a field from a `JsonValueKind.Object`. 51 | assert(obj.kind == JsonValueKind.Object) 52 | obj.objVal[key] = val 53 | 54 | proc `[]=`*(obj: JsonValueRef, index: int, val: JsonValueRef) {.inline.} = 55 | ## Sets a field from a `JsonValueKind.Array`. 56 | assert(obj.kind == JsonValueKind.Array) 57 | obj.arrayVal[index] = val 58 | 59 | proc `{}`*(node: JsonValueRef, keys: varargs[string]): JsonValueRef = 60 | ## Traverses the node and gets the given value. If any of the 61 | ## keys do not exist, returns ``nil``. Also returns ``nil`` if one of the 62 | ## intermediate data structures is not an object. 63 | result = node 64 | for key in keys: 65 | if isNil(result) or result.kind != JsonValueKind.Object: 66 | return nil 67 | result = result.objVal.getOrDefault(key) 68 | 69 | proc getOrDefault*(node: JsonValueRef, key: string): JsonValueRef = 70 | ## Gets a field from a `node`. If `node` is nil or not an object or 71 | ## value at `key` does not exist, returns nil 72 | if not isNil(node) and node.kind == JsonValueKind.Object: 73 | result = node.objVal.getOrDefault(key) 74 | 75 | proc delete*(obj: JsonValueRef, key: string) = 76 | ## Deletes ``obj[key]``. 77 | assert(obj.kind == JsonValueKind.Object) 78 | if not obj.objVal.hasKey(key): 79 | raise newException(IndexDefect, "key not in object") 80 | obj.objVal.del(key) 81 | 82 | func compare*(lhs, rhs: JsonValueRef): bool 83 | 84 | func compareObject(lhs, rhs: JsonValueRef): bool = 85 | ## assume lhs.len >= rhs.len 86 | ## null field and no field are treated equals 87 | for k, v in lhs.objVal: 88 | let rhsVal = rhs.objVal.getOrDefault(k, nil) 89 | if rhsVal.isNil: 90 | if v.kind != JsonValueKind.Null: 91 | return false 92 | else: 93 | continue 94 | if not compare(rhsVal, v): 95 | return false 96 | true 97 | 98 | func compare*(lhs, rhs: JsonValueRef): bool = 99 | ## The difference between `==` and `compare` 100 | ## lies in the object comparison. Null field `compare` 101 | ## to non existent field will return true. 102 | ## On the other hand, `==` will return false. 103 | 104 | if lhs.isNil and rhs.isNil: 105 | return true 106 | 107 | if not lhs.isNil and rhs.isNil: 108 | return false 109 | 110 | if lhs.isNil and not rhs.isNil: 111 | return false 112 | 113 | if lhs.kind != rhs.kind: 114 | return false 115 | 116 | case lhs.kind 117 | of JsonValueKind.String: 118 | lhs.strVal == rhs.strVal 119 | of JsonValueKind.Number: 120 | lhs.numVal == rhs.numVal 121 | of JsonValueKind.Object: 122 | if lhs.objVal.len >= rhs.objVal.len: 123 | compareObject(lhs, rhs) 124 | else: 125 | compareObject(rhs, lhs) 126 | of JsonValueKind.Array: 127 | if lhs.arrayVal.len != rhs.arrayVal.len: 128 | return false 129 | for i, x in lhs.arrayVal: 130 | if not compare(x, rhs.arrayVal[i]): 131 | return false 132 | true 133 | of JsonValueKind.Bool: 134 | lhs.boolVal == rhs.boolVal 135 | of JsonValueKind.Null: 136 | true 137 | 138 | {.pop.} 139 | -------------------------------------------------------------------------------- /docs/src/getting_started.md: -------------------------------------------------------------------------------- 1 | # Getting started 2 | 3 | 4 | 5 | `json_serialization` is used to parse JSON documents directly into Nim types and to encode them back as JSON efficiently. 6 | 7 | Let's start with a simple [JSON-RPC](https://www.jsonrpc.org/specification#examples) example: 8 | 9 | ```json 10 | {"jsonrpc": "2.0", "method": "subtract", "params": [42, 3], "id": 1} 11 | ``` 12 | 13 | ## Imports and exports 14 | 15 | Before we can use `json_serialization`, we have to import the library. 16 | 17 | If you put your custom serialization code in a separate module, make sure to re-export `json_serialization`: 18 | 19 | ```nim 20 | {{#include ../examples/getstarted0.nim:Import}} 21 | ``` 22 | 23 | A common way to organize serialization code is to use a separate module named either after the library (`mylibrary_json_serialization`) or the flavor (`myflavor_json_serialization`). 24 | 25 | For types that mainly exist to interface with JSON, custom serializers can also be placed together with the type definitions. 26 | 27 | ```admonish tip "Re-exports" 28 | When importing a module that contains custom serializers, make sure to re-export it or you might end up with cryptic compiler errors or worse, the default serializers being used! 29 | ``` 30 | 31 | ## Simple reader 32 | 33 | Looking at the example, we'll define a Nim `object` to hold the request data, with matching field names and types: 34 | 35 | ```nim 36 | {{#include ../examples/getstarted0.nim:Request}} 37 | ``` 38 | 39 | `Json.decode` can now turn our JSON input into a `Request`: 40 | ```nim 41 | {{#include ../examples/getstarted0.nim:Decode}} 42 | ``` 43 | 44 | ```admonish tip "" 45 | Replace `decode`/`encode` with `loadFile`/`saveFile` to read and write a file instead! 46 | ``` 47 | 48 | ## Encoding and pretty printing 49 | 50 | Having parsed the example with `Json.decode`, we can pretty-print it back to the console using `Json.encode` that returns a `string`: 51 | 52 | ```nim 53 | {{#include ../examples/getstarted0.nim:Pretty}} 54 | ``` 55 | 56 | ## Handling errors 57 | 58 | Of course, someone might give us some invalid data - `json_serialization` will raise an exception when that happens: 59 | 60 | ```nim 61 | {{#include ../examples/getstarted0.nim:Errors}} 62 | ``` 63 | 64 | The error message points out where things went wrong: 65 | 66 | ```text 67 | Failed to parse document: (1, 8) number expected 68 | ``` 69 | 70 | ## Custom parsing 71 | 72 | Happy we averted a crisis by adding the forgotten exception handler, we go back to the [JSON-RPC specification](https://www.jsonrpc.org/specification#request_object) and notice that strings are actually allowed in the `id` field - further, the only thing we have to do with `id` is to pass it back in the response - we don't really care about its contents. 73 | 74 | We'll define a helper type to deal with this situation and attach some custom parsing code to it that checks the type. Using `JsonString` as underlying storage is an easy way to pass around snippets of JSON whose contents we don't need. 75 | 76 | The custom code is added to `readValue`/`writeValue` procedures that take the stream and our custom type as arguments: 77 | 78 | ```nim 79 | {{#include ../examples/getstarted1.nim:Custom}} 80 | ``` 81 | 82 | ## Flavors and strictness 83 | 84 | While the defaults that `json_serialization` offers are sufficient to get started, implementing JSON-based standards often requires more fine-grained control, such as what to do when a field is missing, unknown or has high-level requirements for parsing and formatting. 85 | 86 | We use `createJsonFlavor` to declare the new flavor passing to it the customization options that we're interested in: 87 | 88 | ```nim 89 | {{#include ../examples/getstarted2.nim:Create}} 90 | ``` 91 | 92 | ## Required and optional fields 93 | 94 | In the JSON-RPC example, both the `jsonrpc` version tag and `method` are required while parameters and `id` can be omitted. Our flavor required all fields to be present except those explicitly optional - we use `Opt` from [results](https://github.com/arnetheduck/nim-results) to select the optional ones: 95 | 96 | ```nim 97 | {{#include ../examples/getstarted2.nim:Request}} 98 | ``` 99 | 100 | ## Automatic object conversion 101 | 102 | The default `Json` flavor allows any `object` to be converted to JSON. If you define a custom serializer and someone forgets to import it, the compiler might end up using the default instead resulting in a nasty runtime surprise. 103 | 104 | `automaticObjectSerialization = false` forces a compiler error for any type that has not opted in to be serialized: 105 | 106 | ```nim 107 | {{#include ../examples/getstarted2.nim:Auto}} 108 | ``` 109 | 110 | With all that work done, we can finally use our custom flavor to encode and decode the `Request`: 111 | 112 | ```nim 113 | {{#include ../examples/getstarted2.nim:Encode}} 114 | ``` 115 | 116 | ## ...almost there! 117 | 118 | While we've covered a fair bit of ground already, our `Request` parser is still not fully standards-compliant - in particular, the list of parameters must be able to handle both positional and named arguments and the values can themselves be full JSON documents that need custom parsing based on the `method` value. 119 | 120 | A more mature JSON-RPC parser can be found in [nim-json-rpc](https://github.com/status-im/nim-json-rpc/blob/master/json_rpc/private/jrpc_sys.nim) which connects the `json_serialization` library to a DSL that conveniently allows mapping Nim procedures to JSON-RPC methods, featuring automatic parameter conversion and other nice conveniences.. 121 | 122 | Furtyher examples of how to use `json_serialization` can be found in the `tests` folder. 123 | 124 | ```admonish tip "Read that spec!" 125 | Not only did we learn to about `json_serialization`, but also that examples are no substitute for reading the spec! 126 | ``` 127 | -------------------------------------------------------------------------------- /json_serialization/format.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | serialization/[formats, object_serialization], 12 | ./types 13 | 14 | from std/json import JsonNode 15 | 16 | export formats, JsonNode 17 | 18 | template generateJsonAutoSerializationAddon*(FLAVOR: typed) {.dirty.} = 19 | generateAutoSerializationAddon(FLAVOR) 20 | 21 | template automaticPrimitivesSerialization*(F: type FLAVOR, enable: static[bool]) = 22 | ## Set all supported primitives automatic serialization flag. 23 | static: 24 | F.setAutoSerialize(string, enable) 25 | F.setAutoSerialize(seq[char], enable) 26 | F.setAutoSerialize(bool, enable) 27 | F.setAutoSerialize(ref, enable) 28 | F.setAutoSerialize(ptr, enable) 29 | F.setAutoSerialize(enum, enable) 30 | F.setAutoSerialize(SomeInteger, enable) 31 | F.setAutoSerialize(SomeFloat, enable) 32 | F.setAutoSerialize(seq, enable) 33 | F.setAutoSerialize(array, enable) 34 | F.setAutoSerialize(cstring, enable) 35 | F.setAutoSerialize(openArray[char], enable) 36 | F.setAutoSerialize(openArray, enable) 37 | F.setAutoSerialize(range, enable) 38 | F.setAutoSerialize(distinct, enable) 39 | 40 | template automaticBuiltinSerialization*(F: type FLAVOR, enable: static[bool]) = 41 | ## Enable or disable all builtin serialization. 42 | automaticPrimitivesSerialization(F, enable) 43 | static: 44 | F.setAutoSerialize(JsonString, enable) 45 | F.setAutoSerialize(JsonNode, enable) 46 | F.setAutoSerialize(JsonNumber, enable) 47 | F.setAutoSerialize(JsonVoid, enable) 48 | F.setAutoSerialize(JsonValueRef, enable) 49 | F.setAutoSerialize(object, enable) 50 | F.setAutoSerialize(tuple, enable) 51 | 52 | 53 | 54 | serializationFormat Json, 55 | mimeType = "application/json" 56 | 57 | template supports*(_: type Json, T: type): bool = 58 | # The JSON format should support every type 59 | true 60 | 61 | type 62 | EnumRepresentation* = enum 63 | EnumAsString 64 | EnumAsNumber 65 | EnumAsStringifiedNumber 66 | 67 | template flavorUsesAutomaticObjectSerialization*(T: type DefaultFlavor): bool = true 68 | template flavorOmitsOptionalFields*(T: type DefaultFlavor): bool = true 69 | template flavorRequiresAllFields*(T: type DefaultFlavor): bool = false 70 | template flavorAllowsUnknownFields*(T: type DefaultFlavor): bool = false 71 | template flavorSkipNullFields*(T: type DefaultFlavor): bool = false 72 | 73 | var DefaultFlavorEnumRep {.compileTime.} = EnumAsString 74 | template flavorEnumRep*(T: type DefaultFlavor): EnumRepresentation = 75 | DefaultFlavorEnumRep 76 | 77 | template flavorEnumRep*(T: type DefaultFlavor, rep: static[EnumRepresentation]) = 78 | static: 79 | DefaultFlavorEnumRep = rep 80 | 81 | # If user choose to use `Json` instead of `DefaultFlavor`, it still goes to `DefaultFlavor` 82 | template flavorEnumRep*(T: type Json, rep: static[EnumRepresentation]) = 83 | static: 84 | DefaultFlavorEnumRep = rep 85 | 86 | when declared(macrocache.hasKey): # Nim 1.6 have no macrocache.hasKey 87 | # Keep backward compatibility behavior, DefaultFlavor always enable all built in serialization. 88 | generateJsonAutoSerializationAddon(DefaultFlavor) 89 | DefaultFlavor.automaticBuiltinSerialization(true) 90 | 91 | # We create overloads of these traits to force the mixin treatment of the symbols 92 | type DummyFlavor* = object 93 | template flavorUsesAutomaticObjectSerialization*(T: type DummyFlavor): bool = true 94 | template flavorOmitsOptionalFields*(T: type DummyFlavor): bool = false 95 | template flavorRequiresAllFields*(T: type DummyFlavor): bool = false 96 | template flavorAllowsUnknownFields*(T: type DummyFlavor): bool = false 97 | template flavorSkipNullFields*(T: type DummyFlavor): bool = false 98 | 99 | when declared(macrocache.hasKey): # Nim 1.6 have no macrocache.hasKey 100 | generateJsonAutoSerializationAddon(DummyFlavor) 101 | DummyFlavor.automaticBuiltinSerialization(false) 102 | 103 | template decode*( 104 | Format: type Json, 105 | inputParam: JsonString, 106 | RecordType: type, 107 | params: varargs[untyped], 108 | ): auto = 109 | decode(Format, string(inputParam), RecordType, params) 110 | 111 | template createJsonFlavor*(FlavorName: untyped, 112 | mimeTypeValue = "application/json", 113 | automaticObjectSerialization = false, 114 | requireAllFields = true, 115 | omitOptionalFields = true, 116 | allowUnknownFields = true, 117 | skipNullFields = false, 118 | automaticPrimitivesSerialization = true) {.dirty.} = 119 | when declared(SerializationFormat): # Earlier versions lack mimeTypeValue 120 | createFlavor(Json, FlavorName, mimeTypeValue) 121 | else: 122 | type FlavorName* = object 123 | 124 | template Reader*(T: type FlavorName): type = Reader(Json, FlavorName) 125 | template Writer*(T: type FlavorName): type = Writer(Json, FlavorName) 126 | template PreferredOutputType*(T: type FlavorName): type = string 127 | template mimeType*(T: type FlavorName): string = mimeTypeValue 128 | 129 | template decode*( 130 | Format: type FlavorName, 131 | inputParam: JsonString, 132 | RecordType: type, 133 | params: varargs[untyped], 134 | ): auto = 135 | decode(Format, string(inputParam), RecordType, params) 136 | 137 | template flavorUsesAutomaticObjectSerialization*(T: type FlavorName): bool = automaticObjectSerialization 138 | template flavorOmitsOptionalFields*(T: type FlavorName): bool = omitOptionalFields 139 | template flavorRequiresAllFields*(T: type FlavorName): bool = requireAllFields 140 | template flavorAllowsUnknownFields*(T: type FlavorName): bool = allowUnknownFields 141 | template flavorSkipNullFields*(T: type FlavorName): bool = skipNullFields 142 | 143 | var `FlavorName EnumRep` {.compileTime.} = EnumAsString 144 | template flavorEnumRep*(T: type FlavorName): EnumRepresentation = 145 | `FlavorName EnumRep` 146 | 147 | template flavorEnumRep*(T: type FlavorName, rep: static[EnumRepresentation]) = 148 | static: 149 | `FlavorName EnumRep` = rep 150 | 151 | when declared(macrocache.hasKey): # Nim 1.6 have no macrocache.hasKey 152 | generateJsonAutoSerializationAddon(FlavorName) 153 | 154 | # Set default to true for backward compatibility 155 | # but user can call it again later with different value. 156 | # Or fine tuning use `Flavor.automaticSerialization(type, true/false)` 157 | FlavorName.automaticBuiltinSerialization(automaticPrimitivesSerialization) 158 | -------------------------------------------------------------------------------- /tests/test_json_flavor.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | std/[strutils, options], 12 | unittest2, 13 | results, 14 | stew/byteutils, 15 | serialization, 16 | ../json_serialization/pkg/results, 17 | ../json_serialization/std/options, 18 | ../json_serialization 19 | 20 | createJsonFlavor StringyJson 21 | 22 | proc writeValue(w: var JsonWriter[StringyJson], value: seq[byte]) = 23 | w.streamElement(s): 24 | s.write('"') 25 | s.write(toHex(value)) 26 | s.write('"') 27 | 28 | proc writeValue*( 29 | w: var JsonWriter[StringyJson], val: SomeInteger) {.raises: [IOError].} = 30 | writeValue(w, $val) 31 | 32 | proc readValue*(r: var JsonReader[StringyJson], v: var SomeSignedInt) = 33 | try: 34 | v = type(v) parseBiggestInt readValue(r, string) 35 | except ValueError as err: 36 | r.raiseUnexpectedValue("A signed integer encoded as string " & err.msg) 37 | 38 | proc readValue*(r: var JsonReader[StringyJson], v: var SomeUnsignedInt) = 39 | try: 40 | v = type(v) parseBiggestUInt readValue(r, string) 41 | except ValueError as err: 42 | r.raiseUnexpectedValue("An unsigned integer encoded as string " & err.msg) 43 | 44 | type 45 | Container = object 46 | name: string 47 | x: int 48 | y: uint64 49 | list: seq[int64] 50 | 51 | OptionalFields = object 52 | one: Opt[string] 53 | two: Option[int] 54 | 55 | SpecialTypes = object 56 | one: JsonVoid 57 | two: JsonNumber[uint64] 58 | three: JsonNumber[string] 59 | four: JsonValueRef[uint64] 60 | 61 | ListOnly = object 62 | list: JsonString 63 | 64 | Container.useDefaultSerializationIn StringyJson 65 | 66 | createJsonFlavor OptJson 67 | OptionalFields.useDefaultSerializationIn OptJson 68 | 69 | const 70 | jsonText = """ 71 | { 72 | "one": "this text will gone", 73 | "two": -789.0009E-19, 74 | "three": 999.776000E+33, 75 | "four" : { 76 | "apple": [1, true, "three"], 77 | "banana": { 78 | "chip": 123, 79 | "z": null, 80 | "v": false 81 | } 82 | } 83 | } 84 | 85 | """ 86 | jsonTextWithNullFields = """ 87 | { 88 | "list": null 89 | } 90 | """ 91 | 92 | createJsonFlavor NullyFields, 93 | skipNullFields = true, 94 | requireAllFields = false 95 | 96 | Container.useDefaultSerializationIn NullyFields 97 | ListOnly.useDefaultSerializationIn NullyFields 98 | 99 | suite "Test JsonFlavor": 100 | test "basic test": 101 | let c = Container(name: "c", x: -10, y: 20, list: @[1'i64, 2, 25]) 102 | let encoded = StringyJson.encode(c) 103 | check encoded == """{"name":"c","x":"-10","y":"20","list":["1","2","25"]}""" 104 | 105 | let decoded = StringyJson.decode(encoded, Container) 106 | check decoded == Container(name: "c", x: -10, y: 20, list: @[1, 2, 25]) 107 | 108 | test "optional fields": 109 | let a = OptionalFields(one: Opt.some("hello")) 110 | let b = OptionalFields(two: some(567)) 111 | let c = OptionalFields(one: Opt.some("burn"), two: some(333)) 112 | 113 | let aa = OptJson.encode(a) 114 | check aa == """{"one":"hello"}""" 115 | 116 | let bb = OptJson.encode(b) 117 | check bb == """{"two":567}""" 118 | 119 | let cc = OptJson.encode(c) 120 | check cc == """{"one":"burn","two":333}""" 121 | 122 | test "Write special types": 123 | let vv = Json.decode(jsonText, SpecialTypes) 124 | let xx = Json.encode(vv) 125 | var ww = Json.decode(xx, SpecialTypes) 126 | ww.three.expSign = JsonSign.Pos # the rest of it should identical to vv 127 | check: 128 | ww == vv 129 | xx == """{"two":-789.0009e-19,"three":999.776000e33,"four":{"apple":[1,true,"three"],"banana":{"chip":123,"z":null,"v":false}}}""" 130 | 131 | test "object with null fields": 132 | expect JsonReaderError: 133 | discard Json.decode(jsonTextWithNullFields, Container) 134 | expect JsonReaderError: 135 | discard Json.decode(JsonString(jsonTextWithNullFields), Container) 136 | 137 | let x = NullyFields.decode(jsonTextWithNullFields, Container) 138 | check x.list.len == 0 139 | 140 | # field should not processed at all 141 | let y = NullyFields.decode(jsonTextWithNullFields, ListOnly) 142 | check y.list.string.len == 0 143 | 144 | test "Enum value representation primitives": 145 | NullyFields.flavorEnumRep(EnumAsString) 146 | when NullyFields.flavorEnumRep() == EnumAsString: 147 | check true 148 | elif NullyFields.flavorEnumRep() == EnumAsNumber: 149 | check false 150 | elif NullyFields.flavorEnumRep() == EnumAsStringifiedNumber: 151 | check false 152 | 153 | NullyFields.flavorEnumRep(EnumAsNumber) 154 | when NullyFields.flavorEnumRep() == EnumAsString: 155 | check false 156 | elif NullyFields.flavorEnumRep() == EnumAsNumber: 157 | check true 158 | elif NullyFields.flavorEnumRep() == EnumAsStringifiedNumber: 159 | check false 160 | 161 | NullyFields.flavorEnumRep(EnumAsStringifiedNumber) 162 | when NullyFields.flavorEnumRep() == EnumAsString: 163 | check false 164 | elif NullyFields.flavorEnumRep() == EnumAsNumber: 165 | check false 166 | elif NullyFields.flavorEnumRep() == EnumAsStringifiedNumber: 167 | check true 168 | 169 | test "Enum value representation of custom flavor": 170 | type 171 | ExoticFruits = enum 172 | DragonFruit 173 | SnakeFruit 174 | StarFruit 175 | 176 | NullyFields.flavorEnumRep(EnumAsNumber) 177 | let u = NullyFields.encode(DragonFruit) 178 | check u == "0" 179 | 180 | NullyFields.flavorEnumRep(EnumAsString) 181 | let v = NullyFields.encode(SnakeFruit) 182 | check v == "\"SnakeFruit\"" 183 | 184 | NullyFields.flavorEnumRep(EnumAsStringifiedNumber) 185 | let w = NullyFields.encode(StarFruit) 186 | check w == "\"2\"" 187 | 188 | test "EnumAsString of custom flavor": 189 | type 190 | Fruit = enum 191 | Banana = "BaNaNa" 192 | Apple = "ApplE" 193 | JackFruit = "VVV" 194 | 195 | NullyFields.flavorEnumRep(EnumAsString) 196 | let u = NullyFields.encode(Banana) 197 | check u == "\"BaNaNa\"" 198 | 199 | let v = NullyFields.encode(Apple) 200 | check v == "\"ApplE\"" 201 | 202 | let w = NullyFields.encode(JackFruit) 203 | check w == "\"VVV\"" 204 | 205 | NullyFields.flavorEnumRep(EnumAsStringifiedNumber) 206 | let x = NullyFields.encode(JackFruit) 207 | check x == "\"2\"" 208 | 209 | NullyFields.flavorEnumRep(EnumAsNumber) 210 | let z = NullyFields.encode(Banana) 211 | check z == "0" 212 | 213 | test "custom writer that uses stream": 214 | let value = @[@[byte 0, 1], @[byte 2, 3]] 215 | check: StringyJson.encode(value) == """["0001","0203"]""" 216 | -------------------------------------------------------------------------------- /tests/test_reader.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | std/json, 12 | faststreams, 13 | unittest2, 14 | serialization, 15 | ../json_serialization/reader 16 | 17 | createJsonFlavor NullFields, 18 | skipNullFields = true 19 | 20 | func toReader(input: string): JsonReader[DefaultFlavor] = 21 | var stream = memoryInput(input) 22 | JsonReader[DefaultFlavor].init(stream) 23 | 24 | func toReaderNullFields(input: string): JsonReader[NullFields] = 25 | var stream = memoryInput(input) 26 | JsonReader[NullFields].init(stream) 27 | 28 | const 29 | jsonText = """ 30 | 31 | { 32 | "string" : "hello world", 33 | "number" : -123.456, 34 | "int": 789, 35 | "bool" : true , 36 | "null" : null , 37 | "array" : [ true, 567.89 , "string in array" , null, [ 123 ] ] 38 | } 39 | 40 | """ 41 | 42 | jsonText2 = """ 43 | 44 | { 45 | "string" : 25, 46 | "number" : 123, 47 | "int": 789, 48 | "bool" : 22 , 49 | "null" : 0 , 50 | } 51 | 52 | """ 53 | 54 | jsonText3 = """ 55 | 56 | { 57 | "one": [1,true,null], 58 | "two": 123, 59 | "three": "help", 60 | "four": "012", 61 | "five": "345", 62 | "six": true, 63 | "seven": 555, 64 | "eight": "mTwo", 65 | "nine": 77, 66 | "ten": 88, 67 | "eleven": 88.55, 68 | "twelve": [true, false], 69 | "thirteen": [3,4], 70 | "fourteen": { 71 | "one": "world", 72 | "two": false 73 | } 74 | } 75 | 76 | """ 77 | 78 | type 79 | MasterEnum = enum 80 | mOne 81 | mTwo 82 | mThree 83 | 84 | SecondObject = object 85 | one: string 86 | two: bool 87 | 88 | MasterReader = object 89 | one: JsonString 90 | two: JsonNode 91 | three: string 92 | four: seq[char] 93 | five: array[3, char] 94 | six: bool 95 | seven: ref int 96 | eight: MasterEnum 97 | nine: int32 98 | ten: float64 99 | eleven: float64 100 | twelve: seq[bool] 101 | thirteen: array[mTwo..mThree, int] 102 | fourteen: SecondObject 103 | 104 | SpecialTypes = object 105 | `string`: JsonVoid 106 | `number`: JsonNumber[uint64] 107 | `int` : JsonNumber[string] 108 | `bool` : JsonValueRef[uint64] 109 | `null` : JsonValueRef[uint64] 110 | `array` : JsonString 111 | 112 | suite "JsonReader basic test": 113 | test "readArray iterator": 114 | var r = toReader "[false, true, false]" 115 | var list: seq[bool] 116 | for x in r.readArray(bool): 117 | list.add x 118 | check list == @[false, true, false] 119 | 120 | test "readObjectFields iterator": 121 | var r = toReader jsonText 122 | var keys: seq[string] 123 | var vals: seq[string] 124 | for key in r.readObjectFields(string): 125 | keys.add key 126 | let val = r.parseAsString() 127 | vals.add val.string 128 | check keys == @["string", "number", "int", "bool", "null", "array"] 129 | 130 | test "readObject iterator": 131 | var r = toReader jsonText2 132 | var keys: seq[string] 133 | var vals: seq[uint64] 134 | for k, v in r.readObject(string, uint64): 135 | keys.add k 136 | vals.add v 137 | 138 | check: 139 | keys == @["string", "number", "int", "bool", "null"] 140 | vals == @[25'u64, 123, 789, 22, 0] 141 | 142 | test "readValue": 143 | try: 144 | var r = toReader jsonText3 145 | var valOrig: MasterReader 146 | r.readValue(valOrig) 147 | # workaround for https://github.com/nim-lang/Nim/issues/24274 148 | let val = valOrig 149 | # TODO: https://github.com/status-im/nim-unittest2/pull/58 150 | doAssert val.seven[] == 555 151 | check: 152 | val.one == JsonString("[1,true,null]") 153 | val.two.num == 123 154 | val.three == "help" 155 | val.four == "012" 156 | val.five == "345" 157 | val.six == true 158 | #val.seven[] == 555 159 | val.eight == mTwo 160 | val.nine == 77 161 | val.ten == 88 162 | val.eleven == 88.55 163 | val.twelve == [true, false] 164 | val.thirteen == [3,4] 165 | val.fourteen == SecondObject(one: "world", two: false) 166 | 167 | except JsonReaderError as ex: 168 | when nimvm: 169 | debugEcho "jsonText3", ex.msg 170 | else: 171 | debugEcho ex.formatMsg("jsonText3") 172 | check false 173 | 174 | test "Special Types": 175 | var r = toReader jsonText 176 | var val: SpecialTypes 177 | r.readValue(val) 178 | 179 | check: 180 | val.`number`.sign == JsonSign.Neg 181 | val.`number`.integer == 123 182 | val.`number`.fraction == "456" 183 | val.`int`.integer == "789" 184 | val.`bool`.kind == JsonValueKind.Bool 185 | val.`bool`.boolVal == true 186 | val.`null`.kind == JsonValueKind.Null 187 | val.`array`.string == """[true,567.89,"string in array",null,[123]]""" 188 | 189 | proc execReadObjectFields(r: var JsonReader): int = 190 | for key in r.readObjectFields(): 191 | let val = r.parseAsString() 192 | discard val 193 | inc result 194 | 195 | test "readObjectFields of null fields": 196 | var r = toReaderNullFields("""{"something":null, "bool":true, "string":null}""") 197 | check execReadObjectFields(r) == 1 198 | 199 | var y = toReader("""{"something":null,"bool":true,"string":"moon"}""") 200 | check execReadObjectFields(y) == 3 201 | 202 | var z = toReaderNullFields("""{"something":null,"bool":true,"string":"moon"}""") 203 | check execReadObjectFields(z) == 2 204 | 205 | proc execReadObject(r: var JsonReader): int = 206 | for k, v in r.readObject(string, int): 207 | inc result 208 | 209 | test "readObjectFields of null fields": 210 | var r = toReaderNullFields("""{"something":null, "bool":123, "string":null}""") 211 | check execReadObject(r) == 1 212 | 213 | expect JsonReaderError: 214 | var y = toReader("""{"something":null,"bool":78,"string":345}""") 215 | check execReadObject(y) == 3 216 | 217 | var z = toReaderNullFields("""{"something":null,"bool":999,"string":100}""") 218 | check execReadObject(z) == 2 219 | 220 | test "readValue of array": 221 | var r = toReader "[false, true, false]" 222 | check r.readValue(array[3, bool]) == [false, true, false] 223 | 224 | test "readValue of array error": 225 | var r = toReader "[false, true, false]" 226 | expect JsonReaderError: 227 | discard r.readValue(array[2, bool]) 228 | 229 | test "readValue of object without fields": 230 | type NoFields = object 231 | 232 | block: 233 | var stream = memoryInput(jsonText) 234 | var r = JsonReader[DefaultFlavor].init(stream, allowUnknownFields=true) 235 | 236 | check: 237 | r.readValue(NoFields) == NoFields() 238 | 239 | block: 240 | var stream = memoryInput(jsonText) 241 | var r = JsonReader[DefaultFlavor].init(stream, allowUnknownFields=false) 242 | 243 | expect(JsonReaderError): 244 | discard r.readValue(NoFields) 245 | -------------------------------------------------------------------------------- /json_serialization/reader_desc.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2019-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | {.experimental: "notnil".} 11 | {.push raises: [], gcsafe.} 12 | 13 | import 14 | std/[strformat], 15 | faststreams/inputs, 16 | serialization/[formats, errors, object_serialization], 17 | "."/[format, types, lexer] 18 | 19 | export 20 | inputs, format, types, errors, 21 | DefaultFlavor 22 | 23 | type 24 | JsonReader*[Flavor = DefaultFlavor] = object 25 | lex*: JsonLexer 26 | 27 | JsonReaderError* = object of types.JsonError 28 | line*, col*: int 29 | 30 | UnexpectedField* = object of JsonReaderError 31 | encounteredField*: string 32 | deserializedType*: cstring 33 | 34 | ExpectedTokenCategory* = enum 35 | etValue = "value" 36 | etBool = "bool literal" 37 | etInt = "integer" 38 | etEnumAny = "enum value (int / string)" 39 | etEnumString = "enum value (string)" 40 | etNumber = "number" 41 | etString = "string" 42 | etComma = "comma" 43 | etColon = "colon" 44 | etBracketLe = "array start bracket" 45 | etBracketRi = "array end bracker" 46 | etCurrlyLe = "object start bracket" 47 | etCurrlyRi = "object end bracket" 48 | 49 | GenericJsonReaderError* = object of JsonReaderError 50 | deserializedField*: string 51 | innerException*: ref CatchableError 52 | 53 | UnexpectedTokenError* = object of JsonReaderError 54 | encountedToken*: JsonValueKind 55 | expectedToken*: ExpectedTokenCategory 56 | 57 | UnexpectedValueError* = object of JsonReaderError 58 | 59 | IncompleteObjectError* = object of JsonReaderError 60 | objectType: cstring 61 | 62 | IntOverflowError* = object of JsonReaderError 63 | isNegative: bool 64 | absIntVal: BiggestUInt 65 | 66 | Json.setReader JsonReader 67 | 68 | func valueStr(err: ref IntOverflowError): string = 69 | if err.isNegative: 70 | result.add '-' 71 | result.add($err.absIntVal) 72 | 73 | template tryFmt(expr: untyped): string = 74 | try: expr 75 | except CatchableError as err: err.msg 76 | 77 | method formatMsg*(err: ref JsonReaderError, filename: string): string = 78 | tryFmt: fmt"{filename}({err.line}, {err.col}) Error while reading json file: {err.msg}" 79 | 80 | method formatMsg*(err: ref UnexpectedField, filename: string): string = 81 | tryFmt: fmt"{filename}({err.line}, {err.col}) Unexpected field '{err.encounteredField}' while deserializing {err.deserializedType}" 82 | 83 | method formatMsg*(err: ref UnexpectedTokenError, filename: string): string = 84 | tryFmt: fmt"{filename}({err.line}, {err.col}) Unexpected token '{err.encountedToken}' in place of '{err.expectedToken}'" 85 | 86 | method formatMsg*(err: ref GenericJsonReaderError, filename: string): string = 87 | tryFmt: fmt"{filename}({err.line}, {err.col}) Exception encountered while deserializing '{err.deserializedField}': [{err.innerException.name}] {err.innerException.msg}" 88 | 89 | method formatMsg*(err: ref IntOverflowError, filename: string): string = 90 | tryFmt: fmt"{filename}({err.line}, {err.col}) The value '{err.valueStr}' is outside of the allowed range" 91 | 92 | method formatMsg*(err: ref UnexpectedValueError, filename: string): string = 93 | tryFmt: fmt"{filename}({err.line}, {err.col}) {err.msg}" 94 | 95 | method formatMsg*(err: ref IncompleteObjectError, filename: string): string = 96 | tryFmt: fmt"{filename}({err.line}, {err.col}) Not all required fields were specified when reading '{err.objectType}'" 97 | 98 | func assignLineNumber*(ex: ref JsonReaderError, lex: JsonLexer) = 99 | ex.line = lex.line 100 | ex.col = lex.tokenStartCol 101 | 102 | proc raiseUnexpectedToken*(lex: var JsonLexer, expected: ExpectedTokenCategory) 103 | {.noreturn, raises: [JsonReaderError, IOError].} = 104 | var ex = new UnexpectedTokenError 105 | ex.assignLineNumber(lex) 106 | ex.encountedToken = lex.tokKind 107 | ex.expectedToken = expected 108 | raise ex 109 | 110 | template raiseUnexpectedToken*(reader: JsonReader, expected: ExpectedTokenCategory) = 111 | raiseUnexpectedToken(reader.lex, expected) 112 | 113 | func raiseUnexpectedValue*( 114 | lex: JsonLexer, msg: string) {.noreturn, raises: [JsonReaderError].} = 115 | var ex = new UnexpectedValueError 116 | ex.assignLineNumber(lex) 117 | ex.msg = msg 118 | raise ex 119 | 120 | template raiseUnexpectedValue*(r: JsonReader, msg: string) = 121 | raiseUnexpectedValue(r.lex, msg) 122 | 123 | func raiseIntOverflow*( 124 | lex: JsonLexer, absIntVal: BiggestUInt, isNegative: bool) 125 | {.noreturn, raises: [JsonReaderError].} = 126 | var ex = new IntOverflowError 127 | ex.assignLineNumber(lex) 128 | ex.absIntVal = absIntVal 129 | ex.isNegative = isNegative 130 | raise ex 131 | 132 | template raiseIntOverflow*(r: JsonReader, absIntVal: BiggestUInt, isNegative: bool) = 133 | raiseIntOverflow(r.lex, absIntVal, isNegative) 134 | 135 | func raiseUnexpectedField*( 136 | lex: JsonLexer, fieldName: string, deserializedType: cstring) 137 | {.noreturn, raises: [JsonReaderError].} = 138 | var ex = new UnexpectedField 139 | ex.assignLineNumber(lex) 140 | ex.encounteredField = fieldName 141 | ex.deserializedType = deserializedType 142 | raise ex 143 | 144 | template raiseUnexpectedField*(r: JsonReader, fieldName: string, deserializedType: cstring) = 145 | raiseUnexpectedField(r.lex, fieldName, deserializedType) 146 | 147 | func raiseIncompleteObject*( 148 | lex: JsonLexer, objectType: cstring) 149 | {.noreturn, raises: [JsonReaderError].} = 150 | var ex = new IncompleteObjectError 151 | ex.assignLineNumber(lex) 152 | ex.objectType = objectType 153 | raise ex 154 | 155 | template raiseIncompleteObject*(r: JsonReader, objectType: cstring) = 156 | raiseIncompleteObject(r.lex, objectType) 157 | 158 | func handleReadException*(lex: JsonLexer, 159 | Record: type, 160 | fieldName: string, 161 | field: auto, 162 | err: ref CatchableError) {.raises: [JsonReaderError].} = 163 | var ex = new GenericJsonReaderError 164 | ex.assignLineNumber(lex) 165 | ex.deserializedField = fieldName 166 | ex.innerException = err 167 | raise ex 168 | 169 | template handleReadException*(r: JsonReader, 170 | Record: type, 171 | fieldName: string, 172 | field: auto, 173 | err: ref CatchableError) = 174 | handleReadException(r.lex, Record, fieldName, field, err) 175 | 176 | proc init*(T: type JsonReader, 177 | stream: InputStream, 178 | flags: JsonReaderFlags, 179 | conf: JsonReaderConf = defaultJsonReaderConf): T = 180 | result.lex = JsonLexer.init(stream, flags, conf) 181 | 182 | proc init*(T: type JsonReader, 183 | stream: InputStream, 184 | allowUnknownFields = false, 185 | requireAllFields = false): T = 186 | mixin flavorAllowsUnknownFields, flavorRequiresAllFields 187 | type Flavor = T.Flavor 188 | 189 | var flags = defaultJsonReaderFlags 190 | if allowUnknownFields or flavorAllowsUnknownFields(Flavor): 191 | flags.incl JsonReaderFlag.allowUnknownFields 192 | if requireAllFields or flavorRequiresAllFields(Flavor): 193 | flags.incl JsonReaderFlag.requireAllFields 194 | result.lex = JsonLexer.init(stream, flags) 195 | 196 | {.pop.} 197 | -------------------------------------------------------------------------------- /tests/test_writer.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2024-2025 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | unittest2, 12 | ../json_serialization/pkg/results, 13 | ../json_serialization/std/options, 14 | ../json_serialization 15 | 16 | type 17 | ObjectWithOptionalFields = object 18 | a: Opt[int] 19 | b: Option[string] 20 | c: int 21 | 22 | OWOF = object 23 | a: Opt[int] 24 | b: Option[string] 25 | c: int 26 | 27 | createJsonFlavor YourJson, 28 | omitOptionalFields = false 29 | 30 | createJsonFlavor MyJson, 31 | omitOptionalFields = true 32 | 33 | ObjectWithOptionalFields.useDefaultSerializationIn YourJson 34 | ObjectWithOptionalFields.useDefaultSerializationIn MyJson 35 | 36 | type 37 | FruitX = enum 38 | BananaX = "BaNaNa" 39 | AppleX = "ApplE" 40 | GrapeX = "VVV" 41 | 42 | Drawer = enum 43 | One 44 | Two 45 | 46 | FruitX.configureJsonSerialization(EnumAsString) 47 | Json.configureJsonSerialization(Drawer, EnumAsNumber) 48 | MyJson.configureJsonSerialization(Drawer, EnumAsString) 49 | 50 | proc writeValue*(w: var JsonWriter, val: OWOF) 51 | {.gcsafe, raises: [IOError].} = 52 | w.writeObject(OWOF): 53 | w.writeField("a", val.a) 54 | w.writeField("b", val.b) 55 | w.writeField("c", val.c) 56 | 57 | func toReader(input: string): JsonReader[DefaultFlavor] = 58 | var stream = unsafeMemoryInput(input) 59 | JsonReader[DefaultFlavor].init(stream) 60 | 61 | suite "Test writer": 62 | test "stdlib option top level some YourJson": 63 | var val = some(123) 64 | let json = YourJson.encode(val) 65 | check json == "123" 66 | 67 | test "stdlib option top level none YourJson": 68 | var val = none(int) 69 | let json = YourJson.encode(val) 70 | check json == "null" 71 | 72 | test "stdlib option top level some MyJson": 73 | var val = some(123) 74 | let json = MyJson.encode(val) 75 | check json == "123" 76 | 77 | test "stdlib option top level none MyJson": 78 | var val = none(int) 79 | let json = MyJson.encode(val) 80 | check json == "null" 81 | 82 | test "results option top level some YourJson": 83 | var val = Opt.some(123) 84 | let json = YourJson.encode(val) 85 | check json == "123" 86 | 87 | test "results option top level none YourJson": 88 | var val = Opt.none(int) 89 | let json = YourJson.encode(val) 90 | check json == "null" 91 | 92 | test "results option top level some MyJson": 93 | var val = Opt.some(123) 94 | let json = MyJson.encode(val) 95 | check json == "123" 96 | 97 | test "results option top level none MyJson": 98 | var val = Opt.none(int) 99 | let json = MyJson.encode(val) 100 | check json == "null" 101 | 102 | test "stdlib option array some YourJson": 103 | var val = [some(123), some(345)] 104 | let json = YourJson.encode(val) 105 | check json == "[123,345]" 106 | 107 | test "stdlib option array none YourJson": 108 | var val = [some(123), none(int), some(777)] 109 | let json = YourJson.encode(val) 110 | check json == "[123,null,777]" 111 | 112 | test "stdlib option array some MyJson": 113 | var val = [some(123), some(345)] 114 | let json = MyJson.encode(val) 115 | check json == "[123,345]" 116 | 117 | test "stdlib option array none MyJson": 118 | var val = [some(123), none(int), some(777)] 119 | let json = MyJson.encode(val) 120 | check json == "[123,null,777]" 121 | 122 | test "results option array some YourJson": 123 | var val = [Opt.some(123), Opt.some(345)] 124 | let json = YourJson.encode(val) 125 | check json == "[123,345]" 126 | 127 | test "results option array none YourJson": 128 | var val = [Opt.some(123), Opt.none(int), Opt.some(777)] 129 | let json = YourJson.encode(val) 130 | check json == "[123,null,777]" 131 | 132 | test "results option array some MyJson": 133 | var val = [Opt.some(123), Opt.some(345)] 134 | let json = MyJson.encode(val) 135 | check json == "[123,345]" 136 | 137 | test "results option array none MyJson": 138 | var val = [Opt.some(123), Opt.none(int), Opt.some(777)] 139 | let json = MyJson.encode(val) 140 | check json == "[123,null,777]" 141 | 142 | test "object with optional fields": 143 | let x = ObjectWithOptionalFields( 144 | a: Opt.some(123), 145 | b: some("nano"), 146 | c: 456, 147 | ) 148 | 149 | let y = ObjectWithOptionalFields( 150 | a: Opt.none(int), 151 | b: none(string), 152 | c: 999, 153 | ) 154 | 155 | let u = YourJson.encode(x) 156 | check u == """{"a":123,"b":"nano","c":456}""" 157 | 158 | let v = YourJson.encode(y) 159 | check v == """{"a":null,"b":null,"c":999}""" 160 | 161 | let xx = MyJson.encode(x) 162 | check xx == """{"a":123,"b":"nano","c":456}""" 163 | 164 | let yy = MyJson.encode(y) 165 | check yy == """{"c":999}""" 166 | 167 | test "writeField with object with optional fields": 168 | let x = OWOF( 169 | a: Opt.some(123), 170 | b: some("nano"), 171 | c: 456, 172 | ) 173 | 174 | let y = OWOF( 175 | a: Opt.none(int), 176 | b: none(string), 177 | c: 999, 178 | ) 179 | 180 | let xx = MyJson.encode(x) 181 | check xx == """{"a":123,"b":"nano","c":456}""" 182 | let yy = MyJson.encode(y) 183 | check yy == """{"c":999}""" 184 | 185 | let uu = YourJson.encode(x) 186 | check uu == """{"a":123,"b":"nano","c":456}""" 187 | let vv = YourJson.encode(y) 188 | check vv == """{"a":null,"b":null,"c":999}""" 189 | 190 | test "Enum value representation primitives": 191 | DefaultFlavor.flavorEnumRep(EnumAsString) 192 | when DefaultFlavor.flavorEnumRep() == EnumAsString: 193 | check true 194 | elif DefaultFlavor.flavorEnumRep() == EnumAsNumber: 195 | check false 196 | elif DefaultFlavor.flavorEnumRep() == EnumAsStringifiedNumber: 197 | check false 198 | 199 | DefaultFlavor.flavorEnumRep(EnumAsNumber) 200 | when DefaultFlavor.flavorEnumRep() == EnumAsString: 201 | check false 202 | elif DefaultFlavor.flavorEnumRep() == EnumAsNumber: 203 | check true 204 | elif DefaultFlavor.flavorEnumRep() == EnumAsStringifiedNumber: 205 | check false 206 | 207 | DefaultFlavor.flavorEnumRep(EnumAsStringifiedNumber) 208 | when DefaultFlavor.flavorEnumRep() == EnumAsString: 209 | check false 210 | elif DefaultFlavor.flavorEnumRep() == EnumAsNumber: 211 | check false 212 | elif DefaultFlavor.flavorEnumRep() == EnumAsStringifiedNumber: 213 | check true 214 | 215 | test "Enum value representation of DefaultFlavor": 216 | type 217 | ExoticFruits = enum 218 | DragonFruit 219 | SnakeFruit 220 | StarFruit 221 | 222 | DefaultFlavor.flavorEnumRep(EnumAsNumber) 223 | let u = Json.encode(DragonFruit) 224 | check u == "0" 225 | 226 | DefaultFlavor.flavorEnumRep(EnumAsString) 227 | let v = Json.encode(SnakeFruit) 228 | check v == "\"SnakeFruit\"" 229 | 230 | DefaultFlavor.flavorEnumRep(EnumAsStringifiedNumber) 231 | let w = Json.encode(StarFruit) 232 | check w == "\"2\"" 233 | 234 | test "EnumAsString of DefaultFlavor/Json": 235 | type 236 | Fruit = enum 237 | Banana = "BaNaNa" 238 | Apple = "ApplE" 239 | JackFruit = "VVV" 240 | 241 | ObjectWithEnumField = object 242 | fruit: Fruit 243 | 244 | Json.flavorEnumRep(EnumAsString) 245 | let u = Json.encode(Banana) 246 | check u == "\"BaNaNa\"" 247 | 248 | let v = Json.encode(Apple) 249 | check v == "\"ApplE\"" 250 | 251 | let w = Json.encode(JackFruit) 252 | check w == "\"VVV\"" 253 | 254 | Json.flavorEnumRep(EnumAsStringifiedNumber) 255 | let x = Json.encode(JackFruit) 256 | check x == "\"2\"" 257 | 258 | Json.flavorEnumRep(EnumAsNumber) 259 | let z = Json.encode(Banana) 260 | check z == "0" 261 | 262 | let obj = ObjectWithEnumField(fruit: Banana) 263 | let zz = Json.encode(obj) 264 | check zz == """{"fruit":0}""" 265 | 266 | test "Individual enum configuration": 267 | Json.flavorEnumRep(EnumAsNumber) 268 | # Although the flavor config is EnumAsNumber 269 | # FruitX is configured as EnumAsAstring 270 | let z = Json.encode(BananaX) 271 | check z == "\"BaNaNa\"" 272 | 273 | # configuration: Json.configureJsonSerialization(Drawer, EnumAsNumber) 274 | let u = Json.encode(Two) 275 | check u == "1" 276 | 277 | # configuration: MyJson.configureJsonSerialization(Drawer, EnumAsString) 278 | let v = MyJson.encode(One) 279 | check v == "\"One\"" 280 | 281 | test "float writer": 282 | template checkExp(src, res) = 283 | var x = toReader(src) 284 | let y = x.readValue(JsonNumber[uint64]) 285 | let z = Json.encode(y) 286 | check z == res 287 | 288 | checkExp("0.0E-1", "0.0e-1") 289 | checkExp("+0.1e-2", "0.1e-2") 290 | checkExp("-0.2e-9", "-0.2e-9") 291 | checkExp("0.0E+1", "0.0e1") 292 | checkExp("+0.1e+2", "0.1e2") 293 | checkExp("-0.2e+9", "-0.2e9") 294 | 295 | test "escapes": 296 | check Json.encode("\x12") == """"\u0012"""" 297 | check Json.encode("""a\b""") == """"a\\b"""" 298 | 299 | test "Empty object": 300 | type NoFields = object 301 | 302 | check: Json.encode(default(NoFields)) == "{}" 303 | -------------------------------------------------------------------------------- /LICENSE-APACHEv2: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Status Research & Development GmbH 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /docs/src/reference.md: -------------------------------------------------------------------------------- 1 | # Reference 2 | 3 | 4 | 5 | This page provides an overview of the `json_serialization` API - for details, see the 6 | [API reference](./api/). 7 | 8 | ## Parsing 9 | 10 | ### Common API 11 | 12 | JSON parsing uses the [common serialization API](https://github.com/status-im/nim-serialization?tab=readme-ov-file#common-api), supporting both object-based and dynamic JSON documents: 13 | 14 | ```nim 15 | {{#include ../examples/reference0.nim:Decode}} 16 | ``` 17 | 18 | ### Standalone Reader 19 | 20 | A reader can be created from any [faststreams](https://github.com/status-im/nim-faststreams)-compatible stream: 21 | 22 | ```nim 23 | {{#include ../examples/reference0.nim:Reader}} 24 | ``` 25 | 26 | ### Parser options 27 | 28 | Parser options allow you to control the strictness and limits of the parser. Set them by passing to `Json.decode` or when initializing the reader: 29 | 30 | ```nim 31 | let flags = defaultJsonReaderFlags + {allowUnknownFields} 32 | 33 | var conf = defaultJsonReaderConf 34 | conf.nestedDepthLimit = 0 35 | 36 | let native = Json.decode( 37 | rawJson, NimServer, flags = flags, conf = conf) 38 | ``` 39 | 40 | [Flavors](#flavors) can be used to override the defaults for some these options. 41 | 42 | #### Flags 43 | 44 | Flags control aspects of the parser that are not all part of the JSON standard, but commonly found in the wild: 45 | 46 | - **allowUnknownFields [=off]**: Skip unknown fields instead of raising an error. 47 | - **requireAllFields [=off]**: Raise an error if any required field is missing. 48 | - **escapeHex [=off]**: Allow `\xHH` escape sequences, which are not standard but common in some languages. 49 | - **relaxedEscape [=off]**: Allow escaping any character, not just control characters. 50 | - **portableInt [=off]**: Restrict integers to the safe JavaScript range (`-2^53 + 1` to `2^53 - 1`). 51 | - **trailingComma [=on]**: Allow trailing commas after the last object member or array element. 52 | - **allowComments [=on]**: Allow C-style comments (`//...` and `/* ... */`). 53 | - **leadingFraction [=on]**: Accept numbers like `.123`, which are not valid JSON but often used. 54 | - **integerPositiveSign [=on]**: Accept numbers like `+123`, for symmetry with negative numbers. 55 | 56 | #### Limits 57 | 58 | Parser limits are passed to `decode`, similar to flags: 59 | 60 | You can adjust these defaults to suit your needs: 61 | 62 | - **nestedDepthLimit [=512]**: Maximum nesting depth for objects and arrays (0 = unlimited). 63 | - **arrayElementsLimit [=0]**: Maximum number of array elements (0 = unlimited). 64 | - **objectMembersLimit [=0]**: Maximum number of key-value pairs in an object (0 = unlimited). 65 | - **integerDigitsLimit [=128]**: Maximum digits in the integer part of a number. 66 | - **fractionDigitsLimit [=128]**: Maximum digits in the fractional part of a number. 67 | - **exponentDigitsLimit [=32]**: Maximum digits in the exponent part of a number. 68 | - **stringLengthLimit [=0]**: Maximum string length in bytes (0 = unlimited). 69 | 70 | ### Special types 71 | 72 | - **JsonString**: Holds a JSON fragment as a distinct string. 73 | - **JsonVoid**: Skips a valid JSON value. 74 | - **JsonNumber**: Holds a JSON number, including fraction and exponent. 75 | - This is a generic type supporting `uint64` and `string` as parameters. 76 | - The parameter determines the type for the integer and exponent parts. 77 | - If `uint64` is used, overflow or digit limits may apply. 78 | - If `string` is used, only digit limits apply. 79 | - The fraction part is always a string to preserve leading zeros. 80 | - **JsonValueRef**: Holds any valid JSON value, similar to `std/json.JsonNode`, but uses `JsonNumber` instead of `int` or `float`. 81 | 82 | ## Writing 83 | 84 | ### Common API 85 | 86 | Similar to parsing, the [common serialization API](https://github.com/status-im/nim-serialization?tab=readme-ov-file#common-api) is used to produce JSON documents. 87 | 88 | ```nim 89 | {{#include ../examples/reference0.nim:Encode}} 90 | ``` 91 | 92 | ### Standalone Writer 93 | 94 | ```nim 95 | {{#include ../examples/reference0.nim:Writer}} 96 | ``` 97 | 98 | ## Flavors 99 | 100 | Flags and limits are runtime configurations, while a flavor is a compile-time mechanism to prevent conflicts between custom serializers for the same type. For example, a JSON-RPC-based API might require that numbers are formatted as hex strings while the same type exposed through REST should use a number. 101 | 102 | Flavors ensure the compiler selects the correct serializer for each subsystem. Use `useDefaultSerializationIn` to assign serializers of a flavor to a specific type. 103 | 104 | ```nim 105 | # Parameters for `createJsonFlavor`: 106 | 107 | FlavorName: untyped 108 | mimeTypeValue = "application/json" 109 | automaticObjectSerialization = false 110 | requireAllFields = true 111 | omitOptionalFields = true 112 | allowUnknownFields = true 113 | skipNullFields = false 114 | ``` 115 | 116 | ```nim 117 | type 118 | OptionalFields = object 119 | one: Opt[string] 120 | two: Option[int] 121 | 122 | createJsonFlavor OptJson 123 | OptionalFields.useDefaultSerializationIn OptJson 124 | ``` 125 | 126 | - `automaticObjectSerialization`: By default, all object types are accepted by `json_serialization` - disable automatic object serialization to only serialize explicitly allowed types 127 | - `omitOptionalFields`: Writer ignores fields with null values. 128 | - `skipNullFields`: Reader ignores fields with null values. 129 | 130 | ## Custom parsers and writers 131 | 132 | Parsing and writing can be customized by providing overloads for the `readValue` and `writeValue` functions. Overrides are commonly used with a [flavor](#flavors) that prevents automatic object serialization, to avoid that some objects use the default serialization, should an import be forgotten. 133 | 134 | ```nim 135 | # Custom serializers for MyType should match the following signatures 136 | proc readValue*(r: var JsonReader, value: var MyType) {.raises: [IOError, SerializationError].} 137 | proc writeValue*(w: var JsonWriter, value: MyType) {.raises: [IOError].} 138 | 139 | # When flavors are used, add the flavor as well 140 | proc readValue*(r: var JsonReader[MyFlavor], value: var MyType) {.raises: [IOError, SerializationError].} 141 | proc writeValue*(w: var JsonWriter[MyFlavor], value: MyType) {.raises: [IOError].} 142 | ``` 143 | 144 | The JsonReader provides access to the JSON token stream coming out of the lexer. While the token stream can be accessed directly, there are several helpers that make it easier to correctly parse common JSON shapes. 145 | 146 | ### Objects 147 | 148 | Decode objects using the `parseObject` template. To parse values, use helper functions or `readValue`. The `readObject` and `readObjectFields` iterators are also useful for custom object parsers. 149 | 150 | ```nim 151 | proc readValue*(r: var JsonReader, value: var Table[string, int]) = 152 | parseObject(r, key): 153 | value[key] = r.parseInt(int) 154 | ``` 155 | 156 | ### Sets and List-like Types 157 | 158 | Sets and list/array-like structures can be parsed using the `parseArray` template, which supports both indexed and non-indexed forms. 159 | 160 | Built-in `readValue` implementations exist for regular `seq` and `array`. For `set` or set-like types, you must provide your own implementation. 161 | 162 | ```nim 163 | type 164 | HoldArray = object 165 | data: array[3, int] 166 | 167 | HoldSeq = object 168 | data: seq[int] 169 | 170 | WelderFlag = enum 171 | TIG 172 | MIG 173 | MMA 174 | 175 | Welder = object 176 | flags: set[WelderFlag] 177 | 178 | proc readValue*(r: var JsonReader, value: var HoldArray) = 179 | # parseArray with index, `i` can be any valid identifier 180 | r.parseArray(i): 181 | value.data[i] = r.parseInt(int) 182 | 183 | proc readValue*(r: var JsonReader, value: var HoldSeq) = 184 | # parseArray without index 185 | r.parseArray: 186 | let lastPos = value.data.len 187 | value.data.setLen(lastPos + 1) 188 | readValue(r, value.data[lastPos]) 189 | 190 | proc readValue*(r: var JsonReader, value: var Welder) = 191 | # populating set also okay 192 | r.parseArray: 193 | value.flags.incl r.parseInt(int).WelderFlag 194 | ``` 195 | 196 | ## Custom Iterators 197 | 198 | Custom iterators provide access to sub-token elements: 199 | 200 | ```nim 201 | customIntValueIt(r: var JsonReader; body: untyped) 202 | customNumberValueIt(r: var JsonReader; body: untyped) 203 | customStringValueIt(r: var JsonReader; limit: untyped; body: untyped) 204 | customStringValueIt(r: var JsonReader; body: untyped) 205 | ``` 206 | 207 | ## Convenience Iterators 208 | 209 | ```nim 210 | readArray(r: var JsonReader, ElemType: typedesc): ElemType 211 | readObjectFields(r: var JsonReader, KeyType: type): KeyType 212 | readObjectFields(r: var JsonReader): string 213 | readObject(r: var JsonReader, KeyType: type, ValueType: type): (KeyType, ValueType) 214 | ``` 215 | 216 | ## Helper Procedures 217 | 218 | When writing a custom serializer, use these safe and intuitive parsers. Avoid using the lexer directly. 219 | 220 | ```nim 221 | tokKind(r: var JsonReader): JsonValueKind 222 | parseString(r: var JsonReader, limit: int): string 223 | parseString(r: var JsonReader): string 224 | parseBool(r: var JsonReader): bool 225 | parseNull(r: var JsonReader) 226 | parseNumber(r: var JsonReader, T: type): JsonNumber[T: string or uint64] 227 | parseNumber(r: var JsonReader, val: var JsonNumber) 228 | toInt(r: var JsonReader, val: JsonNumber, T: type SomeInteger, portable: bool): T 229 | parseInt(r: var JsonReader, T: type SomeInteger, portable: bool = false): T 230 | toFloat(r: var JsonReader, val: JsonNumber, T: type SomeFloat): T 231 | parseFloat(r: var JsonReader, T: type SomeFloat): T 232 | parseAsString(r: var JsonReader, val: var string) 233 | parseAsString(r: var JsonReader): JsonString 234 | parseValue(r: var JsonReader, T: type): JsonValueRef[T: string or uint64] 235 | parseValue(r: var JsonReader, val: var JsonValueRef) 236 | parseArray(r: var JsonReader; body: untyped) 237 | parseArray(r: var JsonReader; idx: untyped; body: untyped) 238 | parseObject(r: var JsonReader, key: untyped, body: untyped) 239 | parseObjectWithoutSkip(r: var JsonReader, key: untyped, body: untyped) 240 | parseObjectSkipNullFields(r: var JsonReader, key: untyped, body: untyped) 241 | parseObjectCustomKey(r: var JsonReader, keyAction: untyped, body: untyped) 242 | parseJsonNode(r: var JsonReader): JsonNode 243 | skipSingleJsValue(r: var JsonReader) 244 | readRecordValue[T](r: var JsonReader, value: var T) 245 | ``` 246 | 247 | ## JsonWriter Helper Procedures 248 | 249 | See the [API reference](./api/json_serialization/writer.html) 250 | 251 | ## Enums 252 | 253 | ```nim 254 | type 255 | Fruit = enum 256 | Apple = "Apple" 257 | Banana = "Banana" 258 | 259 | Drawer = enum 260 | One 261 | Two 262 | 263 | Number = enum 264 | Three = 3 265 | Four = 4 266 | 267 | Mixed = enum 268 | Six = 6 269 | Seven = "Seven" 270 | ``` 271 | 272 | `json_serialization` automatically detects the expected representation for each enum based on its declaration. 273 | - `Fruit` expects string literals. 274 | - `Drawer` and `Number` expect numeric literals. 275 | - `Mixed` (with both string and numeric values) is disallowed by default. 276 | If the JSON literal does not match the expected style, an exception is raised. 277 | You can configure individual enum types: 278 | 279 | ```nim 280 | configureJsonDeserialization( 281 | T: type[enum], allowNumericRepr: static[bool] = false, 282 | stringNormalizer: static[proc(s: string): string] = strictNormalize) 283 | 284 | # Example: 285 | Mixed.configureJsonDeserialization(allowNumericRepr = true) # Only at top level 286 | ``` 287 | 288 | You can also configure enum encoding at the flavor or type level: 289 | 290 | ```nim 291 | type 292 | EnumRepresentation* = enum 293 | EnumAsString 294 | EnumAsNumber 295 | EnumAsStringifiedNumber 296 | 297 | # Examples: 298 | 299 | # Flavor level 300 | Json.flavorEnumRep(EnumAsString) # Default flavor, can be called from non-top level 301 | Flavor.flavorEnumRep(EnumAsNumber) # Custom flavor, can be called from non-top level 302 | 303 | # Individual enum type, regardless of flavor 304 | Fruit.configureJsonSerialization(EnumAsNumber) # Only at top level 305 | 306 | # Individual enum type for a specific flavor 307 | MyJson.flavorEnumRep(Drawer, EnumAsString) # Only at top level 308 | ``` 309 | -------------------------------------------------------------------------------- /tests/test_parser.nim: -------------------------------------------------------------------------------- 1 | # json-serialization 2 | # Copyright (c) 2023 Status Research & Development GmbH 3 | # Licensed under either of 4 | # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) 5 | # * MIT license ([LICENSE-MIT](LICENSE-MIT)) 6 | # at your option. 7 | # This file may not be copied, modified, or distributed except according to 8 | # those terms. 9 | 10 | import 11 | std/[strutils, os, json], 12 | faststreams, 13 | unittest2, 14 | ../json_serialization/parser, 15 | ../json_serialization/value_ops, 16 | ./utils 17 | 18 | createJsonFlavor NullFields, 19 | skipNullFields = true 20 | 21 | func toReader(input: string): JsonReader[DefaultFlavor] = 22 | var stream = unsafeMemoryInput(input) 23 | JsonReader[DefaultFlavor].init(stream) 24 | 25 | func toReaderNullFields(input: string): JsonReader[NullFields] = 26 | var stream = unsafeMemoryInput(input) 27 | JsonReader[NullFields].init(stream) 28 | 29 | suite "Custom iterators": 30 | test "customIntValueIt": 31 | var value: int 32 | var r = toReader"77663399" 33 | r.customIntValueIt: 34 | value = value * 10 + it 35 | check value == 77663399 36 | 37 | test "customNumberValueIt": 38 | var value: int 39 | var frac: int 40 | var exponent: int 41 | var r = toReader"123.456e789" 42 | r.customNumberValueIt: 43 | if part == IntegerPart: 44 | value = value * 10 + it 45 | elif part == FractionPart: 46 | frac = frac * 10 + it 47 | elif part == ExponentPart: 48 | exponent = exponent * 10 + it 49 | check: 50 | value == 123 51 | frac == 456 52 | exponent == 789 53 | 54 | test "customStringValueIt": 55 | proc customTest() = 56 | var text: string 57 | var r = toReader "\"hello \\t world\"" 58 | r.customStringValueIt: 59 | text.add it 60 | 61 | expect JsonReaderError: 62 | r.customStringValueIt(10): 63 | text.add it 64 | 65 | check text == "hello \t world" 66 | customTest() 67 | 68 | suite "Public parser": 69 | test "parseArray": 70 | proc parse(r: var JsonReader, list: var seq[bool]) 71 | {.gcsafe, raises: [IOError, JsonReaderError].} = 72 | r.parseArray: 73 | list.add r.parseBool() 74 | 75 | var r = toReader"[true, true, false]" 76 | var list: seq[bool] 77 | r.parse(list) 78 | check list.len == 3 79 | check list == @[true, true, false] 80 | 81 | test "parseArray with idx": 82 | proc parse(r: var JsonReader, list: var seq[bool]) 83 | {.gcsafe, raises: [IOError, JsonReaderError].} = 84 | r.parseArray(i): 85 | list.add (i mod 2) == 0 86 | list.add r.parseBool() 87 | 88 | var r = toReader"[true, true, false]" 89 | var list: seq[bool] 90 | r.parse(list) 91 | check list.len == 6 92 | check list == @[true, true, false, true, true, false] 93 | 94 | test "parseObject": 95 | type 96 | Duck = object 97 | id: string 98 | ok: bool 99 | 100 | proc parse(r: var JsonReader, list: var seq[Duck]) = 101 | r.parseObject(key): 102 | list.add Duck( 103 | id: key, 104 | ok: r.parseBool() 105 | ) 106 | 107 | var r = toReader "{\"a\": true, \"b\": false}" 108 | var list: seq[Duck] 109 | r.parse(list) 110 | 111 | check list.len == 2 112 | check list == @[Duck(id:"a", ok:true), Duck(id:"b", ok:false)] 113 | 114 | test "parseNumber uint64": 115 | var r = toReader "-1234.0007e+88" 116 | let val = r.parseNumber(uint64) 117 | check: 118 | val.sign == JsonSign.Neg 119 | val.integer == 1234 120 | val.fraction == "0007" 121 | val.expSign == JsonSign.Pos 122 | val.exponent == 88 123 | 124 | test "parseNumber string": 125 | var r = toReader "-1234.0007e+88" 126 | let val = r.parseNumber(string) 127 | check: 128 | val.sign == JsonSign.Neg 129 | val.integer == "1234" 130 | val.fraction == "0007" 131 | val.expSign == JsonSign.Pos 132 | val.exponent == "88" 133 | 134 | func highPlus(T: type): string = 135 | result = $(T.high) 136 | result[^1] = char(result[^1].int + 1) 137 | 138 | func lowMin(T: type): string = 139 | result = $(T.low) 140 | result[^1] = char(result[^1].int + 1) 141 | 142 | template testParseIntI(T: type) = 143 | var r = toReader $(T.high) 144 | var val = r.parseInt(T) 145 | check val == T.high 146 | 147 | expect JsonReaderError: 148 | var r = toReader highPlus(T) 149 | let val = r.parseInt(T) 150 | discard val 151 | 152 | r = toReader $(T.low) 153 | val = r.parseInt(T) 154 | check val == T.low 155 | 156 | expect JsonReaderError: 157 | var r = toReader lowMin(T) 158 | let val = r.parseInt(T) 159 | discard val 160 | 161 | template testParseIntU(T: type) = 162 | var r = toReader $(T.high) 163 | let val = r.parseInt(T) 164 | check val == T.high 165 | 166 | expect JsonReaderError: 167 | var r = toReader highPlus(T) 168 | let val = r.parseInt(T) 169 | discard val 170 | 171 | test "parseInt uint8": 172 | testParseIntU(uint8) 173 | 174 | test "parseInt int8": 175 | testParseIntI(int8) 176 | 177 | test "parseInt uint16": 178 | testParseIntU(uint16) 179 | 180 | test "parseInt int16": 181 | testParseIntI(int16) 182 | 183 | test "parseInt uint32": 184 | testParseIntU(uint32) 185 | 186 | test "parseInt int32": 187 | testParseIntI(int32) 188 | 189 | test "parseInt uint64": 190 | testParseIntU(uint64) 191 | 192 | test "parseInt int64": 193 | testParseIntI(int64) 194 | 195 | test "parseInt portable overflow": 196 | expect JsonReaderError: 197 | var r = toReader $(minPortableInt - 1) 198 | let val = r.parseInt(int64, true) 199 | discard val 200 | 201 | expect JsonReaderError: 202 | var r = toReader $(maxPortableInt + 1) 203 | let val = r.parseInt(int64, true) 204 | discard val 205 | 206 | when sizeof(int) == 8: 207 | expect JsonReaderError: 208 | var r = toReader $(minPortableInt - 1) 209 | let val = r.parseInt(int, true) 210 | discard val 211 | 212 | expect JsonReaderError: 213 | var r = toReader $(maxPortableInt + 1) 214 | let val = r.parseInt(int, true) 215 | discard val 216 | 217 | test "parseFloat": 218 | var 219 | r = toReader "56.009" 220 | val = r.parseFloat(float64) 221 | check val == 56.009 222 | 223 | r = toReader "-56.009e6" 224 | val = r.parseFloat(float64) 225 | check val == -56009000.0 226 | 227 | proc inputFile(fileName: string): InputStream = 228 | when nimvm: 229 | let data = staticRead(pathRelativeTo(fileName, "tests")) 230 | unsafeMemoryInput(data) 231 | else: 232 | memFileInput(fileName) 233 | 234 | template testParseAsString(fileName: string) = 235 | try: 236 | var stream = inputFile(fileName) 237 | var r = JsonReader[DefaultFlavor].init(stream) 238 | let val = r.parseAsString() 239 | var xr = toReader val.string 240 | let xval = xr.parseAsString() 241 | check val == xval 242 | except JsonReaderError as ex: 243 | when nimvm: 244 | debugEcho fileName, ex.msg 245 | else: 246 | debugEcho ex.formatMsg(fileName) 247 | check false 248 | 249 | test "parseAsString": 250 | for fileName in walkDirRec(transformPath): 251 | let (_, name) = fileName.splitPath() 252 | if name notin allowedToFail: 253 | testParseAsString(fileName) 254 | 255 | for fileName in walkDirRec(parsingPath): 256 | let (_, name) = fileName.splitPath() 257 | if name.startsWith("y_"): 258 | testParseAsString(fileName) 259 | # test cases starts with i_ are allowed to 260 | # fail or success depending on the implementation details 261 | elif name.startsWith("i_"): 262 | if name notin allowedToFail: 263 | testParseAsString(fileName) 264 | 265 | test "parseAsString of null fields": 266 | var r = toReaderNullFields("""{"something":null, "bool":null, "string":null}""") 267 | let res = r.parseAsString() 268 | check res.string == """{"something":null,"bool":null,"string":null}""" 269 | 270 | var y = toReader("""{"something":null, "bool":null, "string":null}""") 271 | let yy = y.parseAsString() 272 | check yy.string == """{"something":null,"bool":null,"string":null}""" 273 | 274 | proc execParseObject(r: var JsonReader): int = 275 | r.parseObject(key): 276 | discard key 277 | let val = r.parseAsString() 278 | discard val 279 | inc result 280 | 281 | test "parseObject of null fields": 282 | var r = toReaderNullFields("""{"something":null, "bool":true, "string":null}""") 283 | check execParseObject(r) == 1 284 | 285 | var y = toReader("""{"something":null,"bool":true,"string":"moon"}""") 286 | check execParseObject(y) == 3 287 | 288 | var z = toReaderNullFields("""{"something":null,"bool":true,"string":"moon"}""") 289 | check execParseObject(z) == 2 290 | 291 | test "parseJsonNode of null fields": 292 | var r = toReaderNullFields("""{"something":null, "bool":true, "string":null}""") 293 | let n = r.parseJsonNode() 294 | check: 295 | n["something"].kind == JNull 296 | n["bool"].kind == JBool 297 | n["string"].kind == JNull 298 | 299 | var y = toReader("""{"something":null,"bool":true,"string":"moon"}""") 300 | let z = y.parseJsonNode() 301 | check: 302 | z["something"].kind == JNull 303 | z["bool"].kind == JBool 304 | z["string"].kind == JString 305 | 306 | test "parseValue of null fields": 307 | var r = toReaderNullFields("""{"something":null, "bool":true, "string":null}""") 308 | let n = r.parseValue(uint64) 309 | check: 310 | n["something"].kind == JsonValueKind.Null 311 | n["bool"].kind == JsonValueKind.Bool 312 | n["string"].kind == JsonValueKind.Null 313 | 314 | var y = toReader("""{"something":null,"bool":true,"string":"moon"}""") 315 | let z = y.parseValue(uint64) 316 | check: 317 | z["something"].kind == JsonValueKind.Null 318 | z["bool"].kind == JsonValueKind.Bool 319 | z["string"].kind == JsonValueKind.String 320 | 321 | test "JsonValueRef comparison": 322 | var x = JsonValueRef[uint64](kind: JsonValueKind.Null) 323 | var n = JsonValueRef[uint64](nil) 324 | check x != n 325 | check n != x 326 | check x == x 327 | check n == n 328 | 329 | const 330 | jsonText = """ 331 | 332 | { 333 | "string" : "hello world", 334 | "number" : -123.456, 335 | "int": 789, 336 | "bool" : true , 337 | "null" : null , 338 | "array" : [ true, 567.89 , "string in array" , null, [ 123 ] ], 339 | "object" : { 340 | "abc" : 444.008 , 341 | "def": false 342 | } 343 | } 344 | 345 | """ 346 | 347 | jsonBigNum = """ 348 | { 349 | "bignum": 9999999999999999999999999999999999999999999, 350 | "float": 124.123, 351 | "int": -12345 352 | } 353 | """ 354 | 355 | suite "Parse to runtime dynamic structure": 356 | test "parse to json node": 357 | var r = toReader(jsonText) 358 | let n = r.parseJsonNode() 359 | check: 360 | n["string"].str == "hello world" 361 | n["number"].fnum == -123.456 362 | n["int"].num == 789 363 | n["bool"].bval == true 364 | n["array"].len == 5 365 | n["array"][0].bval == true 366 | n["array"][1].fnum == 567.89 367 | n["array"][2].str == "string in array" 368 | $n["array"][2] == "\"string in array\"" # quoted string 369 | n["array"][3].kind == JNull 370 | n["array"][4].kind == JArray 371 | n["array"][4].len == 1 372 | n["array"][4][0].num == 123 373 | n["object"]["abc"].fnum == 444.008 374 | n["object"]["def"].bval == false 375 | 376 | test "parseValue": 377 | var r = toReader(jsonText) 378 | let n = r.parseValue(uint64) 379 | check: 380 | n["string"].strVal == "hello world" 381 | n["bool"].boolVal == true 382 | n["int"].numVal.integer == 789 383 | n["array"].len == 5 384 | n["array"][0].boolVal == true 385 | n["array"][2].strVal == "string in array" 386 | n["array"][3].kind == JsonValueKind.Null 387 | n["array"][4].kind == JsonValueKind.Array 388 | n["array"][4].len == 1 389 | n["object"]["def"].boolVal == false 390 | 391 | test "parse to json node bignum": 392 | var r = toReader(jsonBigNum) 393 | let n = r.parseJsonNode() 394 | check: 395 | n["bignum"].kind == JString 396 | n["bignum"].str == "9999999999999999999999999999999999999999999" 397 | $n["bignum"] == "9999999999999999999999999999999999999999999" # unquoted raw string 398 | n["float"].kind == JFloat 399 | n["float"].fnum == 124.123 400 | n["int"].kind == JInt 401 | n["int"].num == -12345 402 | 403 | test "parseValue bignum": 404 | var r = toReader(jsonBigNum) 405 | let n = r.parseValue(string) 406 | check: 407 | n["bignum"].kind == JsonValueKind.Number 408 | n["bignum"].numVal.integer == "9999999999999999999999999999999999999999999" 409 | 410 | test "parseValue bignum overflow": 411 | var r = toReader(jsonBigNum) 412 | expect JsonReaderError: 413 | let n = r.parseValue(uint64) 414 | 415 | test "nim v2 regression #23233": 416 | # Nim compiler bug #23233 will prevent 417 | # compilation if both JsonValueRef[uint64] and JsonValueRef[string] 418 | # are instantiated at together. 419 | var r1 = toReader(jsonText) 420 | let n1 = r1.parseValue(uint64) 421 | check n1["int"].numVal.integer == 789 422 | 423 | var r2 = toReader(jsonText) 424 | let n2 = r2.parseValue(string) 425 | check n2["int"].numVal.integer == "789" 426 | --------------------------------------------------------------------------------