Skip to content

Commit

Permalink
Add comment support in JSON (jsonc)
Browse files Browse the repository at this point in the history
  • Loading branch information
wait-what committed Feb 26, 2024
1 parent eafd514 commit ad353eb
Show file tree
Hide file tree
Showing 2 changed files with 113 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,35 @@ impl DeJsonState {
self.tok = DeJsonTok::Eof;
return Ok(());
}
if self.cur == '/' {
self.next(i);
match self.cur {
'/' => {
while self.cur != '\n' && self.cur != '\0' {
self.next(i);
}
return self.next_tok(i);
}
'*' => {
let mut last = self.cur;
loop {
self.next(i);
if self.cur == '\0' {
return Err(self.err_token("MultiLineCommentClose"));
}
if last == '*' && self.cur == '/' {
self.next(i);
break;
}
last = self.cur;
}
return self.next_tok(i);
}
_ => {
return Err(self.err_token("CommentOpen"));
}
}
}
match self.cur {
':' => {
self.next(i);
Expand Down
84 changes: 84 additions & 0 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,90 @@ fn de() {
assert_eq!(test.c, None);
}

#[test]
fn de_inline_comment() {
#[derive(DeJson)]
pub struct Test {
pub a: Option<String>,
}

let json = r#"{ //comment
// comment
"a": "// asd"// comment
} // comment"#;

let test: Test = DeJson::deserialize_json(json).unwrap();
assert_eq!(test.a.unwrap(), "// asd");
}

#[test]
fn de_multiline_comment() {
#[derive(DeJson)]
pub struct Test {
pub a: f32,
}

let json = r#"{ /* multiline
comment */
"a": 1 /* multiline *
comment */
} /** multiline **/"#;

let test: Test = DeJson::deserialize_json(json).unwrap();
assert_eq!(test.a, 1.);
}

#[test]
fn de_illegal_inline_comment() {
#[derive(DeJson)]
pub struct Test {
pub a: f32,
}

let jsons = vec![
r#"{
"a": // comment,
}"#,
r#"{
/ comment
"a": 1,
}"#,
];

for json in jsons {
let test: Result<Test, _> = DeJson::deserialize_json(json);
assert!(test.is_err());
}
}

#[test]
fn de_illegal_multiline_comment() {
#[derive(DeJson)]
pub struct Test {
pub a: f32,
}

let jsons = vec![
r#"{
/* /* comment */ */
"a": 1
}"#,
r#"{
/* comment
"a": 1
}"#,
r#"{
*/
"a": 1
}"#,
];

for json in jsons {
let test: Result<Test, _> = DeJson::deserialize_json(json);
assert!(test.is_err());
}
}

#[test]
fn de_reorder() {
#[derive(DeJson)]
Expand Down

0 comments on commit ad353eb

Please sign in to comment.