Skip to content

Commit 4cb2c3a

Browse files
committed
Implement valid_json?
1 parent dd95c68 commit 4cb2c3a

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

ext/rapidjson/cext.cc

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,20 @@ VALUE parse(VALUE _self, VALUE string) {
4040
return handler.GetRoot();
4141
}
4242

43+
VALUE valid_json_p(VALUE _self, VALUE string) {
44+
NullHandler handler;
45+
Reader reader;
46+
char *cstring = StringValueCStr(string); // fixme?
47+
StringStream ss(cstring);
48+
ParseResult ok = reader.Parse(ss, handler);
49+
50+
if (!ok) {
51+
return Qfalse;
52+
}
53+
54+
return Qtrue;
55+
}
56+
4357
extern "C" void
4458
Init_rapidjson(void)
4559
{
@@ -50,6 +64,7 @@ Init_rapidjson(void)
5064

5165
rb_define_module_function(rb_mRapidjson, "parse", parse, 1);
5266
rb_define_module_function(rb_mRapidjson, "load", parse, 1);
67+
rb_define_module_function(rb_mRapidjson, "valid_json?", valid_json_p, 1);
5368

5469
rb_eParseError = rb_define_class_under(rb_mRapidjson, "ParseError", rb_eStandardError);
5570
rb_eEncodeError = rb_define_class_under(rb_mRapidjson, "EncodeError", rb_eStandardError);

ext/rapidjson/parser.hh

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
using namespace rapidjson;
66

7+
class NullHandler : public BaseReaderHandler<UTF8<>, NullHandler> {
8+
};
9+
710
struct RubyObjectHandler : public BaseReaderHandler<UTF8<>, RubyObjectHandler> {
811
bool Null() {
912
return PutValue(Qnil);

test/test_jsonchecker.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,14 @@ class TestJsonchecker < Minitest::Test
1212
define_method(:"test_#{name}") do
1313
original_json = File.read(filename)
1414
if name.start_with?("fail") && !exclude
15+
refute RapidJSON.valid_json?(original_json)
1516
ex = assert_raises RapidJSON::ParseError do
1617
RapidJSON.parse(original_json)
1718
end
1819
re = /JSON parse error: .* \(\d+\)\z/
1920
assert_match re, ex.message
2021
else
22+
assert RapidJSON.valid_json?(original_json)
2123
assert RapidJSON.parse(original_json)
2224
end
2325
end

0 commit comments

Comments
 (0)