使用json-mask 查詢json 資料
阿新 • • 發佈:2020-08-29
我們在處理json 資料的時候很多時候會需要部分json 資料,一般的處理方式是jsonpath,jmeshpath ,jsonselect
json-mask 是另外一個不錯的選擇(很遺憾不是標準,目前只有js 的實現),而且json-mask 的好處是可以保留資料
介面,以下是一個簡單的學習
語言說明
a,b,c 選擇多個欄位
a/b/c 從父節點,選擇子欄位
a(b,c) 從父節點,選擇多個欄位
a/*/c 萬用字元模式,選擇所有元素指定的欄位
環境準備
- 專案結構
yarn init -y
yarn add json-mask
- 程式碼
app.js:
const mask = require("json-mask")
var fields = 'url,object(content,attachments/url)';
var originalObj = {
id: 'z12gtjhq3qn2xxl2o224exwiqruvtda0i',
url: 'https://plus.google.com/102817283354809142195/posts/F97fqZwJESL',
object: {
objectType: 'note',
content:
'A picture... of a space ship... launched from earth 40 years ago.',
attachments: [
{
objectType: 'image',
url: 'http://apod.nasa.gov/apod/ap110908.html',
image: { height: 284, width: 506 }
}
]
},
provider: { title: 'Google+' }
};
var maskedObj = mask(originalObj, fields);
console.log(JSON.stringify(maskedObj))
- 效果
node app.js | jq .
{
"url": "https://plus.google.com/102817283354809142195/posts/F97fqZwJESL",
"object": {
"content": "A picture... of a space ship... launched from earth 40 years ago.",
"attachments": [
{
"url": "http://apod.nasa.gov/apod/ap110908.html"
}
]
}
}
說明
json-mask 同時提供了一個框架中介軟體的實現比如express