2021-01-12 14:29:47 +08:00
|
|
|
## JSON 扩展函数
|
|
|
|
|
|
|
|
### 1.json\_load
|
2021-01-13 15:49:25 +08:00
|
|
|
|
|
|
|
> 加载 json 数据。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
json_load(str) => object
|
|
|
|
json_load(binary) => object
|
|
|
|
json_load(data, size) => object
|
|
|
|
```
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
### 2.json\_save
|
2021-01-13 15:49:25 +08:00
|
|
|
|
2021-07-29 14:34:17 +08:00
|
|
|
> 将对象保存为 json 数据。
|
2021-01-13 15:49:25 +08:00
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
2021-07-29 14:34:17 +08:00
|
|
|
json_save(obj) => binary
|
2021-01-13 15:49:25 +08:00
|
|
|
```
|
|
|
|
|
2021-09-09 15:10:12 +08:00
|
|
|
### 3.json\_save\_to\_string
|
|
|
|
|
|
|
|
> 将对象保存为字符串数据。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
json_save_to_string(obj) => string
|
|
|
|
```
|
|
|
|
|
|
|
|
### 4.ubjson\_load
|
2021-01-13 15:49:25 +08:00
|
|
|
|
|
|
|
> 加载 ubjson 数据。
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
|
|
|
ubjson_load(binary) => object
|
|
|
|
ubjson_load(data, size) => object
|
|
|
|
```
|
|
|
|
|
2021-09-09 15:10:12 +08:00
|
|
|
### 5.ubjson\_save
|
2021-01-12 14:29:47 +08:00
|
|
|
|
2021-07-29 14:34:17 +08:00
|
|
|
> 将对象保存为 ubjson 数据。
|
2021-01-13 15:49:25 +08:00
|
|
|
----------------------------
|
|
|
|
|
|
|
|
#### 原型
|
|
|
|
|
|
|
|
```js
|
2021-07-29 14:34:17 +08:00
|
|
|
ubjson_save(obj) => binary
|
2021-01-13 15:49:25 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
### 完整示例
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
```js
|
|
|
|
//load from string
|
2021-09-09 15:10:12 +08:00
|
|
|
str='{
|
|
|
|
"name" : "fscript",
|
|
|
|
"age" : 100
|
|
|
|
}'
|
|
|
|
a=json_load(str)
|
2021-01-12 14:29:47 +08:00
|
|
|
|
|
|
|
assert(object_get(a, "name")=="fscript");
|
|
|
|
assert(object_get(a, "age")==100);
|
|
|
|
|
|
|
|
//save to file
|
|
|
|
b=json_save(a)
|
|
|
|
assert(file_write("test.json", b))
|
|
|
|
|
2021-09-09 15:10:12 +08:00
|
|
|
//json obj to string
|
|
|
|
c=json_save_to_string(a)
|
|
|
|
assert(c==str);
|
|
|
|
|
2021-01-12 14:29:47 +08:00
|
|
|
//load from file as text
|
|
|
|
a = json_load(file_read_text("test.json"))
|
|
|
|
|
|
|
|
assert(object_get(a, "name")=="fscript");
|
|
|
|
assert(object_get(a, "age")==100);
|
|
|
|
|
|
|
|
//load from file as binary
|
|
|
|
a = json_load(file_read_binary("test.json"))
|
|
|
|
assert(file_remove("test.json"))
|
|
|
|
|
|
|
|
assert(object_get(a, "name")=="fscript");
|
|
|
|
assert(object_get(a, "age")==100);
|
|
|
|
|
|
|
|
assert(file_remove("test.json"))
|
|
|
|
unset(a)
|
|
|
|
unset(b)
|
2021-09-09 15:10:12 +08:00
|
|
|
unset(c)
|
|
|
|
unset(str)
|
2021-01-12 14:29:47 +08:00
|
|
|
```
|