make json.loads accept bytes

This commit is contained in:
blueloveTH 2023-10-31 21:34:30 +08:00
parent 2f3017ebfd
commit a7448b7fa0
5 changed files with 19 additions and 7 deletions

View File

@ -112,8 +112,13 @@ void add_module_cjson(VM* vm){
cJSON_InitHooks(&hooks); cJSON_InitHooks(&hooks);
vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args){ vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args){
const Str& string = CAST(Str&, args[0]); std::string_view sv;
cJSON *json = cJSON_ParseWithLength(string.data, string.size); if(is_non_tagged_type(args[0], vm->tp_bytes)){
sv = PK_OBJ_GET(Bytes, args[0]).sv();
}else{
sv = CAST(Str&, args[0]).sv();
}
cJSON *json = cJSON_ParseWithLength(sv.data(), sv.size());
if(json == NULL){ if(json == NULL){
const char* start = cJSON_GetErrorPtr(); const char* start = cJSON_GetErrorPtr();
const char* end = start; const char* end = start;

View File

@ -9,11 +9,11 @@ pkpy has two JSON modules.
**Their interfaces are the same.** `cjson` is faster while the built-in `json` is more stable since it was developed earlier. **Their interfaces are the same.** `cjson` is faster while the built-in `json` is more stable since it was developed earlier.
### `json.loads(s)` ### `json.loads(data: str | bytes)`
Decode a JSON string into a python object. Decode a JSON string into a python object.
### `json.dumps(obj)` ### `json.dumps(obj) -> str`
Encode a python object into a JSON string. Encode a python object into a JSON string.

View File

@ -1,2 +1,2 @@
def loads(string: str) -> object: ... def loads(data: str | bytes) -> object: ...
def dumps(obj: object) -> str: ... def dumps(obj: object) -> str: ...

View File

@ -1509,8 +1509,13 @@ void add_module_sys(VM* vm){
void add_module_json(VM* vm){ void add_module_json(VM* vm){
PyObject* mod = vm->new_module("json"); PyObject* mod = vm->new_module("json");
vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args) { vm->bind_func<1>(mod, "loads", [](VM* vm, ArgsView args) {
const Str& expr = CAST(Str&, args[0]); std::string_view sv;
CodeObject_ code = vm->compile(expr, "<json>", JSON_MODE); if(is_non_tagged_type(args[0], vm->tp_bytes)){
sv = PK_OBJ_GET(Bytes, args[0]).sv();
}else{
sv = CAST(Str&, args[0]).sv();
}
CodeObject_ code = vm->compile(sv, "<json>", JSON_MODE);
return vm->_exec(code, vm->top_frame()->_module); return vm->_exec(code, vm->top_frame()->_module);
}); });

View File

@ -29,6 +29,8 @@ assert json.loads("true") == True
assert json.loads("false") == False assert json.loads("false") == False
assert json.loads("{}") == {} assert json.loads("{}") == {}
assert json.loads(b"false") == False
_j = json.dumps(a) _j = json.dumps(a)
_a = json.loads(_j) _a = json.loads(_j)