Coverage for agentos/marketplace/skills/json-toolkit/json-toolkit.py: 3%

67 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-07-06 12:29 +0800

1""" 

2json-toolkit — JSON 解析、查询、格式化工具。 

3 

4Category: data 

5""" 

6 

7 

8def run( 

9 action: str, 

10 file_path: str = "", 

11 json_str: str = "", 

12 query: str = "", 

13 output_path: str = "", 

14 indent: int = 2, 

15) -> str: 

16 """JSON 操作工具。action: parse/query/format/validate。query 用点号路径如 'users.0.name'。""" 

17 import json 

18 import os 

19 

20 def _load(): 

21 if file_path and os.path.isfile(file_path): 

22 with open(file_path, encoding="utf-8") as f: 

23 return json.load(f) 

24 if json_str: 

25 return json.loads(json_str) 

26 return None 

27 

28 def _query_path(obj, path): 

29 for key in path.split("."): 

30 if obj is None: 

31 return None 

32 if isinstance(obj, list): 

33 try: 

34 obj = obj[int(key)] 

35 except (ValueError, IndexError): 

36 return None 

37 elif isinstance(obj, dict): 

38 obj = obj.get(key) 

39 else: 

40 return None 

41 return obj 

42 

43 try: 

44 if action == "validate": 

45 data = _load() 

46 if data is None: 

47 return "[json-toolkit] 无有效输入" 

48 return f"有效 JSON。类型: {type(data).__name__}" 

49 if action == "format": 

50 data = _load() 

51 if data is None: 

52 return "[json-toolkit] 无有效输入" 

53 formatted = json.dumps(data, ensure_ascii=False, indent=indent) 

54 if output_path: 

55 with open(output_path, "w", encoding="utf-8") as f: 

56 f.write(formatted) 

57 return f"已格式化写入: {output_path}" 

58 return formatted 

59 if action == "query": 

60 data = _load() 

61 if data is None: 

62 return "[json-toolkit] 无有效输入" 

63 if not query: 

64 return "[json-toolkit] query 不能为空" 

65 result = _query_path(data, query) 

66 if result is None: 

67 return f"[json-toolkit] 路径 '{query}' 无匹配" 

68 if isinstance(result, (dict, list)): 

69 return json.dumps(result, ensure_ascii=False, indent=indent) 

70 return str(result) 

71 if action == "parse": 

72 data = _load() 

73 if data is None: 

74 return "[json-toolkit] 无有效输入" 

75 if isinstance(data, dict): 

76 keys = list(data.keys()) 

77 return f"JSON 对象, {len(keys)} 个顶层键: {', '.join(keys[:30])}" 

78 if isinstance(data, list): 

79 return f"JSON 数组, {len(data)} 个元素" 

80 return f"JSON 值: {data}" 

81 return f"[json-toolkit] 未知操作: {action}, 支持: parse/query/format/validate" 

82 except json.JSONDecodeError as e: 

83 return f"[json-toolkit] JSON 解析错误: {e}" 

84 except Exception as e: 

85 return f"[json-toolkit] 失败: {e}" 

86 

87 

88__all__ = ["run"]