README.md - Rust

This commit is contained in:
freestrings 2019-03-06 18:55:21 +09:00
parent 728345d6a6
commit c3e5f61642
4 changed files with 522 additions and 202 deletions

433
README.md
View File

@ -13,52 +13,87 @@ To enjoy Rust
*(not yet published `jsonpath-wasm`)* *(not yet published `jsonpath-wasm`)*
```javascript ```javascript
// browser
import * as jsonpath from "jsonpath-wasm"; import * as jsonpath from "jsonpath-wasm";
// nodejs
let jsonpath = require('jsonpath-wasm');
``` ```
#### `read` 함수 #### `read` 함수
``` ```javascript
jsonpath.read(JSON.parse("{\"a\" : 1}"), "$.a"); let jsonObj = {
jsonpath.read("{\"a\" : 1}", "$.a"); "school": {
``` "friends": [{"id": 0}, {"id": 1}]
},
"friends": [{"id": 0}, {"id": 1}]
};
let ret = [{"id": 0}, {"id": 0}];
let a = jsonpath.read(JSON.stringify(jsonObj), "$..friends[0]");
let b = jsonpath.read(jsonObj, "$..friends[0]");
console.log(
JSON.stringify(ret) == JSON.stringify(a),
JSON.stringify(a) == JSON.stringify(b)
);
```
#### JsonPath 재사용 #### JsonPath 재사용
``` ```javascript
let template = jsonpath.compile("$.a"); let template = jsonpath.compile("$..friends[0]");
// let jsonObj = {
// 1. read json string "school": {
// "friends": [ {"id": 0}, {"id": 1} ]
template("{\"a\" : 1}") },
"friends": [ {"id": 0}, {"id": 1} ]
};
// let ret = [ {"id": 0}, {"id": 0} ];
// 2. read as json object
// // 1. read as json object
template(JSON.parse("{\"a\" : 1}")); console.log(JSON.stringify(template(jsonObj)) == JSON.stringify(ret));
// 2. read as json string
console.log(JSON.stringify(template(JSON.stringify(jsonObj))) == JSON.stringify(ret));
let jsonObj2 = {
"school": {
"friends": [ {"name": "Millicent Norman"}, {"name": "Vincent Cannon"} ]
},
"friends": [ {"id": 0}, {"id": 1} ]
};
let ret2 = [ {"id": 0}, {"name": "Millicent Norman"} ];
// 1. read as json object
console.log(JSON.stringify(template(jsonObj2)) == JSON.stringify(ret2));
// 2. read as json string
console.log(JSON.stringify(template(JSON.stringify(jsonObj2))) == JSON.stringify(ret2));
``` ```
#### Json 재사용 #### Json 재사용
``` ```javascript
// let jsonObj = {
// 1. read json string "school": {
// "friends": [{"id": 0}, {"id": 1}]
let reader1 = jsonpath.reader("{\"a\" : 1}"); },
reader1("$.a"); "friends": [{"id": 0},{"id": 1}]
reader1("$.b"); };
// // 1. read as json object
// 2. read as json object let reader = jsonpath.reader(jsonObj);
// console.log(JSON.stringify(reader("$..friends[0]")) == JSON.stringify([ {"id": 0}, {"id": 0} ]));
let reader2 = jsonpath.reader(JSON.parse("{\"a\" : 1}")); console.log(JSON.stringify(reader("$..friends[1]")) == JSON.stringify([ {"id": 1}, {"id": 1} ]));
reader2("$.a");
reader2("$.b"); // 2. read as json string
let reader2 = jsonpath.reader(JSON.stringify(jsonObj));
console.log(JSON.stringify(reader2("$..friends[0]")) == JSON.stringify([ {"id": 0}, {"id": 0} ]));
console.log(JSON.stringify(reader2("$..friends[1]")) == JSON.stringify([ {"id": 1}, {"id": 1} ]));
``` ```
### 데모 ### 예제
**Demo**: https://freestrings.github.io/jsonpath/ **Demo**: https://freestrings.github.io/jsonpath/
@ -126,7 +161,347 @@ json 데이터 *(참고 사이트: https://github.com/json-path/JsonPath)*
## With Rust (as library) ## With Rust (as library)
- ```rust
extern crate jsonpath_lib as jsonpath;
#[macro_use]
extern crate serde_json;
```
#### `read` 함수
```rust
let json_obj = json!({
"school": {
"friends": [{"id": 0}, {"id": 1}]
},
"friends": [{"id": 0}, {"id": 1}]
});
let json = jsonpath::read(json_obj, "$..friends[0]").unwrap();
let ret = json!([ {"id": 0}, {"id": 0} ]);
assert_eq!(json, ret)
```
#### JsonPath 재사용
```rust
let mut template = jsonpath::compile("$..friends[0]");
let json_obj = json!({
"school": {
"friends": [ {"id": 0}, {"id": 1} ]
},
"friends": [ {"id": 0}, {"id": 1} ]
});
let json = template(json_obj).unwrap();
let ret = json!([ {"id": 0}, {"id": 0} ]);
assert_eq!(json, ret);
let json_obj = json!({
"school": {
"friends": [ {"name": "Millicent Norman"}, {"name": "Vincent Cannon"} ]
},
"friends": [ {"id": 0}, {"id": 1} ]
});
let json = template(json_obj).unwrap();
let ret = json!([ {"id": 0}, {"name": "Millicent Norman"} ]);
assert_eq!(json, ret);
```
#### Json 재사용
```rust
let json_obj = json!({
"school": {
"friends": [{"id": 0}, {"id": 1}]
},
"friends": [{"id": 0},{"id": 1}]
});
let mut reader = jsonpath::reader(json_obj);
let json = reader("$..friends[0]").unwrap();
let ret = json!([ {"id": 0}, {"id": 0} ]);
assert_eq!(json, ret);
let json = reader("$..friends[1]").unwrap();
let ret = json!([ {"id": 1}, {"id": 1} ]);
assert_eq!(json, ret);
```
#### 예제
```rust
let json_obj = json!({
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
});
let mut reader = jsonpath::reader(json_obj);
//
// $.store.book[*].author
//
let json = reader("$.store.book[*].author").unwrap();
let ret = json!([
"Nigel Rees",
"Evelyn Waugh",
"Herman Melville",
"J. R. R. Tolkien"
]);
assert_eq!(json, ret);
//
// $..author
//
let json = reader("$..author").unwrap();
let ret = json!([
"Nigel Rees",
"Evelyn Waugh",
"Herman Melville",
"J. R. R. Tolkien"
]);
assert_eq!(json, ret);
//
// $.store.*
//
let json = reader("$.store.*").unwrap();
let ret = json!([
[
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
{
"color": "red",
"price": 19.95
}
]);
assert_eq!(ret, json);
//
// $.store..price
//
let json = reader("$.store..price").unwrap();
let ret = json!([8.95, 12.99, 8.99, 22.99, 19.95]);
assert_eq!(ret, json);
//
// $..book[2]
//
let json = reader("$..book[2]").unwrap();
let ret = json!([{
"category" : "fiction",
"author" : "Herman Melville",
"title" : "Moby Dick",
"isbn" : "0-553-21311-3",
"price" : 8.99
}]);
assert_eq!(ret, json);
//
// $..book[-2]
//
let json = reader("$..book[-2]").unwrap();
let ret = json!([{
"category" : "fiction",
"author" : "Herman Melville",
"title" : "Moby Dick",
"isbn" : "0-553-21311-3",
"price" : 8.99
}]);
assert_eq!(ret, json);
//
// $..book[0,1]
//
let json = reader("$..book[0,1]").unwrap();
let ret = json!([
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
]);
assert_eq!(ret, json);
//
// $..book[:2]
//
let json = reader("$..book[:2]").unwrap();
let ret = json!([
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
]);
assert_eq!(ret, json);
//
// $..book[2:]
//
let json = reader("$..book[2:]").unwrap();
let ret = json!([
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
]);
assert_eq!(ret, json);
//
// $..book[?(@.isbn)]
//
let json = reader("$..book[?(@.isbn)]").unwrap();
let ret = json!([
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
]);
assert_eq!(ret, json);
//
// $.store.book[?(@.price < 10)]
//
let json = reader("$.store.book[?(@.price < 10)]").unwrap();
let ret = json!([
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
}
]);
assert_eq!(ret, json);
//
// $..book[?((@.price == 12.99 || $.store.bicycle.price < @.price) || @.category == "reference")]
//
let json = reader("$..book[?((@.price == 12.99 || $.store.bicycle.price < @.price) || @.category == "reference")]").unwrap();
let ret = json!([
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
},
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}
]);
assert_eq!(ret, json);
```
## With AWS API Gateway ## With AWS API Gateway

View File

@ -257,12 +257,12 @@ impl JsonValueFilter {
pub fn new(json: &str) -> result::Result<Self, String> { pub fn new(json: &str) -> result::Result<Self, String> {
let json: Value = serde_json::from_str(json) let json: Value = serde_json::from_str(json)
.map_err(|e| e.description().to_string())?; .map_err(|e| e.description().to_string())?;
Ok(JsonValueFilter::new_from_value(json)) Ok(JsonValueFilter::new_from_value(Rc::new(Box::new(json))))
} }
pub fn new_from_value(json: Value) -> Self{ pub fn new_from_value(json: Rc<Box<Value>>) -> Self {
JsonValueFilter { JsonValueFilter {
json: Rc::new(Box::new(json)), json: json,
filter_stack: Vec::new(), filter_stack: Vec::new(),
token_stack: Vec::new(), token_stack: Vec::new(),
term_stack: Vec::new(), term_stack: Vec::new(),

View File

@ -49,22 +49,21 @@
//! // //! //
//! // $.store.book[*].author //! // $.store.book[*].author
//! // //! //
//! let json = reader("$.store.book[*].author"); //! let json = reader("$.store.book[*].author").unwrap();
//! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]); //! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]);
//! assert_eq!(json, ret); //! assert_eq!(json, ret);
//! //!
//! // //! //
//! // $..author //! // $..author
//! // //! //
//! let json = reader("$..author"); //! let json = reader("$..author").unwrap();
//! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]); //! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]);
//! assert_eq!(json, ret); //! assert_eq!(json, ret);
//! //!
//! // //! //
//! // $.store.* //! // $.store.*
//! // //! //
//! let json = reader("$.store.*"); //! let json = reader("$.store.*").unwrap();
//! let ret = json!(["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]);
//! let ret = json!([ //! let ret = json!([
//! [ //! [
//! {"category" : "reference", "author" : "Nigel Rees","title" : "Sayings of the Century", "price" : 8.95}, //! {"category" : "reference", "author" : "Nigel Rees","title" : "Sayings of the Century", "price" : 8.95},
@ -79,14 +78,14 @@
//! // //! //
//! // $.store..price //! // $.store..price
//! // //! //
//! let json = reader("$.store..price"); //! let json = reader("$.store..price").unwrap();
//! let ret = json!([8.95, 12.99, 8.99, 22.99, 19.95]); //! let ret = json!([8.95, 12.99, 8.99, 22.99, 19.95]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//! //!
//! // //! //
//! // $..book[2] //! // $..book[2]
//! // //! //
//! let json = reader("$..book[2]"); //! let json = reader("$..book[2]").unwrap();
//! let ret = json!([{ //! let ret = json!([{
//! "category" : "fiction", //! "category" : "fiction",
//! "author" : "Herman Melville", //! "author" : "Herman Melville",
@ -99,7 +98,7 @@
//! // //! //
//! // $..book[-2] //! // $..book[-2]
//! // //! //
//! let json = reader("$..book[-2]"); //! let json = reader("$..book[-2]").unwrap();
//! let ret = json!([{ //! let ret = json!([{
//! "category" : "fiction", //! "category" : "fiction",
//! "author" : "Herman Melville", //! "author" : "Herman Melville",
@ -112,110 +111,53 @@
//! // //! //
//! // $..book[0,1] //! // $..book[0,1]
//! // //! //
//! let json = reader("$..book[0,1]"); //! let json = reader("$..book[0,1]").unwrap();
//! let ret = json!([ //! let ret = json!([
//! { //! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! "category" : "reference", //! {"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99}
//! "author" : "Nigel Rees",
//! "title" : "Sayings of the Century",
//! "price" : 8.95
//! },
//! {
//! "category" : "fiction",
//! "author" : "Evelyn Waugh",
//! "title" : "Sword of Honour",
//! "price" : 12.99
//! }
//! ]); //! ]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//! //!
//! // //! //
//! // $..book[:2] //! // $..book[:2]
//! // //! //
//! let json = reader("$..book[:2]"); //! let json = reader("$..book[:2]").unwrap();
//! let ret = json!([ //! let ret = json!([
//! { //! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! "category" : "reference", //! {"category" : "fiction","author" : "Evelyn Waugh","title" : "Sword of Honour","price" : 12.99}
//! "author" : "Nigel Rees",
//! "title" : "Sayings of the Century",
//! "price" : 8.95
//! },
//! {
//! "category" : "fiction",
//! "author" : "Evelyn Waugh",
//! "title" : "Sword of Honour",
//! "price" : 12.99
//! }
//! ]); //! ]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//! //!
//! // //! //
//! // $..book[2:] //! // $..book[2:]
//! // //! //
//! let json = reader("$..book[2:]"); //! let json = reader("$..book[2:]").unwrap();
//! let ret = json!([ //! let ret = json!([
//! { //! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99},
//! "category" : "fiction", //! {"category" : "fiction","author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99}
//! "author" : "Herman Melville",
//! "title" : "Moby Dick",
//! "isbn" : "0-553-21311-3",
//! "price" : 8.99
//! },
//! {
//! "category" : "fiction",
//! "author" : "J. R. R. Tolkien",
//! "title" : "The Lord of the Rings",
//! "isbn" : "0-395-19395-8",
//! "price" : 22.99
//! }
//! ]); //! ]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//! //!
//! // //! //
//! // $..book[?(@.isbn)] //! // $..book[?(@.isbn)]
//! // //! //
//! let json = reader("$..book[?(@.isbn)]"); //! let json = reader("$..book[?(@.isbn)]").unwrap();
//! let ret = json!([ //! let ret = json!([
//! { //! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99},
//! "category" : "fiction", //! {"category" : "fiction","author" : "J. R. R. Tolkien","title" : "The Lord of the Rings","isbn" : "0-395-19395-8","price" : 22.99}
//! "author" : "Herman Melville",
//! "title" : "Moby Dick",
//! "isbn" : "0-553-21311-3",
//! "price" : 8.99
//! },
//! {
//! "category" : "fiction",
//! "author" : "J. R. R. Tolkien",
//! "title" : "The Lord of the Rings",
//! "isbn" : "0-395-19395-8",
//! "price" : 22.99
//! }
//! ]); //! ]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//! //!
//! // //! //
//! // $.store.book[?(@.price < 10)] //! // $.store.book[?(@.price < 10)]
//! // //! //
//! let json = reader("$.store.book[?(@.price < 10)]"); //! let json = reader("$.store.book[?(@.price < 10)]").unwrap();
//! let ret = json!([ //! let ret = json!([
//! { //! {"category" : "reference","author" : "Nigel Rees","title" : "Sayings of the Century","price" : 8.95},
//! "category" : "reference", //! {"category" : "fiction","author" : "Herman Melville","title" : "Moby Dick","isbn" : "0-553-21311-3","price" : 8.99}
//! "author" : "Nigel Rees",
//! "title" : "Sayings of the Century",
//! "price" : 8.95
//! },
//! {
//! "category" : "fiction",
//! "author" : "Herman Melville",
//! "title" : "Moby Dick",
//! "isbn" : "0-553-21311-3",
//! "price" : 8.99
//! }
//! ]); //! ]);
//! assert_eq!(ret, json); //! assert_eq!(ret, json);
//!
//! ``` //! ```
//!
#[macro_use] #[macro_use]
extern crate log; extern crate log;
extern crate env_logger; extern crate env_logger;
@ -239,6 +181,7 @@ use parser::parser::*;
use filter::value_filter::*; use filter::value_filter::*;
use std::result; use std::result;
use std::rc::Rc;
use serde_json::Value; use serde_json::Value;
type Result = result::Result<Value, String>; type Result = result::Result<Value, String>;
@ -278,7 +221,7 @@ pub fn compile<'a>(path: &'a str) -> impl FnMut(Value) -> Result + 'a {
move |json| { move |json| {
match &node { match &node {
Ok(n) => { Ok(n) => {
let mut jf = JsonValueFilter::new_from_value(json); let mut jf = JsonValueFilter::new_from_value(Rc::new(Box::new(json)));
jf.visit(n.clone()); jf.visit(n.clone());
Ok(jf.take_value()) Ok(jf.take_value())
} }
@ -309,8 +252,9 @@ pub fn compile<'a>(path: &'a str) -> impl FnMut(Value) -> Result + 'a {
/// assert_eq!(json, ret); /// assert_eq!(json, ret);
/// ``` /// ```
pub fn reader(json: Value) -> impl FnMut(&str) -> Result { pub fn reader(json: Value) -> impl FnMut(&str) -> Result {
let mut jf = JsonValueFilter::new_from_value(json); let n = Rc::new(Box::new(json));
move |path: &str| { move |path: &str| {
let mut jf = JsonValueFilter::new_from_value(n.clone());
let mut parser = Parser::new(path); let mut parser = Parser::new(path);
parser.parse(&mut jf)?; parser.parse(&mut jf)?;
Ok(jf.take_value()) Ok(jf.take_value())
@ -326,12 +270,12 @@ pub fn reader(json: Value) -> impl FnMut(&str) -> Result {
/// }, /// },
/// "friends": [{"id": 0}, {"id": 1}] /// "friends": [{"id": 0}, {"id": 1}]
/// }); /// });
/// let mut reader = jsonpath::read(json_obj, "$..friends[0]"); /// let json = jsonpath::read(json_obj, "$..friends[0]").unwrap();
/// let ret = json!([ {"id": 0}, {"id": 0} ]); /// let ret = json!([ {"id": 0}, {"id": 0} ]);
/// assert_eq!(json, ret); /// assert_eq!(json, ret);
/// ``` /// ```
pub fn read(json: Value, path: &str) -> Result { pub fn read(json: Value, path: &str) -> Result {
let mut jf = JsonValueFilter::new_from_value(json); let mut jf = JsonValueFilter::new_from_value(Rc::new(Box::new(json)));
let mut parser = Parser::new(path); let mut parser = Parser::new(path);
parser.parse(&mut jf)?; parser.parse(&mut jf)?;
Ok(jf.take_value()) Ok(jf.take_value())

View File

@ -9,6 +9,7 @@ mod utils;
use cfg_if::cfg_if; use cfg_if::cfg_if;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use std::result::Result; use std::result::Result;
use std::rc::Rc;
use serde_json::Value; use serde_json::Value;
use jsonpath::parser::parser::*; use jsonpath::parser::parser::*;
@ -23,7 +24,7 @@ cfg_if! {
} }
fn filter_value(json: Value, node: Node) -> JsValue { fn filter_value(json: Value, node: Node) -> JsValue {
let mut jf = JsonValueFilter::new_from_value(json); let mut jf = JsonValueFilter::new_from_value(Rc::new(Box::new(json)));
jf.visit(node); jf.visit(node);
let taken = jf.take_value(); let taken = jf.take_value();
match JsValue::from_serde(&taken) { match JsValue::from_serde(&taken) {