JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,它易于閱讀和編寫。要將 JSON 對象轉換為其他格式,首先需要了解目標格式。以下是將 JSON 對象轉換為其他常見格式的方法:
import json
def 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 xml
json_string = '{"name": "John", "age": 30, "city": "New York"}'
json_obj = json.loads(json_string)
xml_output = json_to_xml(json_obj)
print(xml_output)
import json
import csv
def 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')
import json
import yaml
def 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。如果您使用其他編程語言,可以查找相應的庫來實現類似的功能。在進行格式轉換時,請確保安裝了所需的庫。