Skip to main content

json

Function json 

Source
pub fn json(text: &str) -> Result<Json, Refused>
Expand description

Parses text as JSON, the way JSON.parse does without a reviver: no comments, no trailing commas, no single quotes, no byte order mark. A key given twice keeps its first place and its last value. Spans in a refusal are byte offsets in text.

Use it for state a page keeps as JSON in a script element of its own, like Next.js’s <script id="__NEXT_DATA__" type="application/json"> or Nuxt 3’s __NUXT_DATA__: pass the element’s text. Nuxt 3’s is in devalue’s format, a flat array whose numbers point at other entries, which this reads as the array it is.

use parsec_js::data::json;

let v = json(r#"{"props": {"pageProps": {"id": 7}}, "page": "/item"}"#).unwrap();
assert_eq!(v.to_json_string(), r#"{"props":{"pageProps":{"id":7}},"page":"/item"}"#);
assert_eq!(json("[1,]").unwrap_err().reason, "json-syntax");