Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fyl080801/json-to-object
https://github.com/fyl080801/json-to-object
Last synced: 4 days ago
JSON representation
- Host: GitHub
- URL: https://github.com/fyl080801/json-to-object
- Owner: fyl080801
- Created: 2020-09-21T15:43:46.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2020-10-15T08:17:26.000Z (about 4 years ago)
- Last Synced: 2024-10-12T08:26:22.917Z (about 1 month ago)
- Language: TypeScript
- Size: 161 KB
- Stars: 0
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# JSON TO OBJECT
## 特性
json 格式可以转换成 js 对象,但是只能描述对象的属性,通过 json-to-object 可以实现定制化的转换,将特定属性按照自定义规则进行转换
## 使用
```bash
npm i json-to-object
```## 示例
```javascript
import { createTransform } from 'json-to-object';// 传入的数据
const context = { model: { text: 'aaa' } };const transform = createTransform()
.useContext(context)
// 自定义转换,关联 model 里的 text
.useProvider({
getter: (prop, owner) => {
return typeof owner[prop] === 'object' && owner[prop].$type === 'bind';
},
deal: (prop, owner, options) => {
const value = owner[prop];
const { context } = options;Object.defineProperty(owner, prop, {
get() {
return context[value.$source];
},
});
},
})
// 自定义转换,转换成 function
.useProvider({
getter: (prop, owner) => {
return typeof owner[prop] === 'object' && owner[prop].$type === 'on';
},
deal: (prop, owner, options) => {
const value = owner[prop];Object.defineProperty(owner, prop, {
get() {
return new Function(value.$result);
},
});
},
});const result = transform.transform({
fields: [
{ component: 'p', text: { $type: 'bind', $source: 'model.text' } },
{
component: 'button',
events: [
{
name: 'click',
handler: { $type: 'on', $result: "alert('aaa')" },
},
],
},
],
});
```