Function jsonc_to_json::jsonc_to_json
source · pub fn jsonc_to_json(jsonc: &str) -> Cow<'_, str>
Expand description
Removes all JSON with Comments parts from jsonc
, turning it into
valid JSON, i.e. removing line comments, block comments, and trailing
commas.
- Line comments, e.g.
// Line Comment
- Block comments, e.g.
/* Block Comment */
- Trailing commas, e.g.
[1,2,3,,]
->[1,2,3]
If jsonc
is already valid JSON, then Cow::Borrowed(jsonc)
is returned, otherwise a new String
is allocated and Cow::Owned
is returned.
Warning: The conversion is infallible and does not validate jsonc
.
If it contains invalid JSON or invalid JSON with Comments, then the
invalid parts are included in the result, i.e. {foo,/*comment*/bar,}
is turned into {foo,bar}
.
See also jsonc_to_json_into()
for an alternative variant, that reuses
an already allocated String
.
Example
See also serde_json
example in crate root docs.
use jsonc_to_json::{jsonc_to_json, jsonc_to_json_into};
let jsonc = "{\"arr\": [1, 2,/* Comment */ 3, 4,,]}// Line Comment";
let json = jsonc_to_json(jsonc);
println!("{}", json);
Which outputs the following:
{"arr": [1, 2, 3, 4]}