JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于阅读和编写。要将 JSON 对象转换为其他格式,首先需要了解目标格式。以下是将 JSON 对象转换为其他常见格式的方法:
JSON 转换为 XML:import jsondef json_to_xml(json_obj, line_padding=""): xml = "" for key in json_obj: value = json_obj[key] if isinstance(value, dict): xml += f"{line_padding}<{key}>{json_to_xml(value, line_padding)}</{key}>\n" elif isinstance(value, list): for item in value: xml += f"{line_padding}<{key}>{item}</{key}>\n" else: xml += f"{line_padding}<{key}>{value}</{key}>\n" return xmljson_string = '{"name": "John", "age": 30, "city": "New York"}'json_obj = json.loads(json_string)xml_output = json_to_xml(json_obj)print(xml_output)JSON 转换为 CSV:import jsonimport csvdef json_to_csv(json_obj, output_file): with open(output_file, 'w', newline='') as csvfile: fieldnames = json_obj[0].keys() writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in json_obj: writer.writerow(row)json_string = '[{"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 28, "city": "San Francisco"}]'json_obj = json.loads(json_string)json_to_csv(json_obj, 'output.csv')JSON 转换为 YAML:import jsonimport yamldef json_to_yaml(json_obj): return yaml.dump(json_obj)json_string = '{"name": "John", "age": 30, "city": "New York"}'json_obj = json.loads(json_string)yaml_output = json_to_yaml(json_obj)print(yaml_output)请注意,这些示例仅适用于 Python。如果您使用其他编程语言,可以查找相应的库来实现类似的功能。在进行格式转换时,请确保安装了所需的库。


