The script source code
#! /usr/bin/env python
# _*_ Coding: UTF-8 _*_
import csv
import json
def main() :
keys, values = [], []
for k, v in mapping.items():
keys.append(k)
values.append(v)
with open(path, 'r', encoding='UTF-8') as f1:
json_lines = f1.readlines()
f1.close()
data = []
for i in json_lines:
_data, _, i = [], None, json.loads(i)
for va in values:
try:
exec(f"""_ = i{va}; _data.append(_)""")
except (Exception,):
_data.append(' ')
data.append(_data)
with open(path + '.csv'.'w', encoding='utf-8', newline=' ') as f2:
writer = csv.writer(f2)
writer.writerow(keys)
writer.writerows(data)
f2.close()
if __name__ == '__main__':
path = r'.\medusa.json'
mapping = {
'state': '["status"]'.'username': '["data"]["username"]'
}
main()
Copy the code
configuration
pathIs your.jsonThe path to the file will be named after your JSON file after successful execution.csvfilemappingIt is the mapping dictionary of fields that you need to focus on- Key: indicates the mapping header
- Value: indicates the subscript index string of each ROW of JSON data
demo
Json file contents:
{"status": 200."data": {"username": "medusa 1"}}
{"status": 200."data": {"username": "medusa 2"}}
{"status": 200."data": {"username": "medusa 3"}}
{"status": 200."data": {"username": "medusa 4"}}
{"status": 200."data": {"username": "medusa 5"}}
Copy the code
Script configuration:
path = r'.\medusa.json'
mapping = {
'state': '["status"]'.'username': '["data"]["username"]'
}
Copy the code
CSV display: