Function pjson::parse[][src]

pub fn parse<F>(json: &[u8], opts: usize, iter: F) -> i64 where
    F: FnMut(usize, usize, usize) -> i64

Parse JSON. The iter function is a callback that fires for every element in the JSON document. Elements include all values and tokens. The ‘start’ and ‘end’ params are the start and end indexes of their respective element, such that json[start..end] will equal the complete element data. The ‘info’ param provides extra information about the element data.

Returning 0 from ‘iter’ will stop the parsing. Returning 1 from ‘iter’ will continue the parsing. Returning -1 from ‘iter’ will skip all children elements in the current Object or Array, which only applies when the ‘info’ for current element has the Open bit set, otherwise it effectively works like returning 1.

This operation returns zero or a negative value if an error occured. This value represents the position that the parser was at when it discovered the error. To get the true offset multiple this value by -1.

This operation returns a positive value when successful. If the ‘iter’ stopped early then this value will be the position the parser was at when it stopped, otherwise the value will be equal the length of the original json document.

The following example prints every JSON String Value in the document:

fn main() {
    let json = br#"
    {
      "name": {"first": "Tom", "last": "Anderson"},
      "age":37,
      "children": ["Sara","Alex","Jack"],
      "fav.movie": "Deer Hunter",
      "friends": [
    	{"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    	{"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    	{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
      ]
    }
   "#;

   pjson::parse(json, 0, |start: usize, end: usize, info: usize| -> i64 {
       if info & (pjson::STRING | pjson::VALUE) == pjson::STRING | pjson::VALUE {
           let el = String::from_utf8(json[start..end].to_vec()).unwrap();
           println!("{}", el);
       }
       1
   });
}
// output:
// "Tom"
// "Anderson"
// "Sara"
// "Alex"
// "Jack"
// "Deer Hunter"
// "Dale"
// "Murphy"
// "ig"
// "fb"
// "tw"
// "Roger"
// "Craig"
// "fb"
// "tw"
// "Jane"
// "Murphy"
// "ig"
// "tw"