Outils pour utilisateurs

Outils du site


tech:script_python_conversion_json_vers_csv

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
tech:script_python_conversion_json_vers_csv [2026/11/07 23:07] – Jean-Baptistetech:script_python_conversion_json_vers_csv [2026/11/11 15:45] (Version actuelle) – Jean-Baptiste
Ligne 9: Ligne 9:
 ~~~python ~~~python
 #! /usr/bin/env python3 #! /usr/bin/env python3
- +
 import sys import sys
 import json import json
 import argparse import argparse
-  + 
-parser = argparse.ArgumentParser( +parser = argparse.ArgumentParser(epilog="""Convert JSON file to CSV.""")
-    epilog="""Convert JSON file to CSV.""")+
  
 parser.add_argument("-i", help="Input JSON file") parser.add_argument("-i", help="Input JSON file")
-parser.add_argument("-o", help="Output XLS file")+parser.add_argument("-o", help="Output CSV file")
 args = parser.parse_args() args = parser.parse_args()
- + 
 def concat(a, b): def concat(a, b):
-    a=str(a) +    a = str(a) 
-    b=str(b) +    b = str(b) 
-    return a+ "_" + b+    return a + "_" + b 
  
 def quote_string(thing): def quote_string(thing):
Ligne 31: Ligne 32:
     else:     else:
         return thing         return thing
 +
  
 def recursiv_if_json_dict(k, v): def recursiv_if_json_dict(k, v):
Ligne 36: Ligne 38:
         for k2, v2 in v.items():         for k2, v2 in v.items():
             recursiv_if_json_dict(concat(k, k2), v2)             recursiv_if_json_dict(concat(k, k2), v2)
-    else: +    else:
         write(k, v)         write(k, v)
 +
  
 def recursiv_if_json_list(thing): def recursiv_if_json_list(thing):
Ligne 48: Ligne 51:
                 new_list.append(elm)                 new_list.append(elm)
     return new_list     return new_list
-         + 
 def convert_json2csv(): def convert_json2csv():
     with open(args.i, "r") as json_file:     with open(args.i, "r") as json_file:
         json_load = json.load(json_file)         json_load = json.load(json_file)
- +
         if isinstance(json_load, dict):         if isinstance(json_load, dict):
             for k, v in json_load.items():             for k, v in json_load.items():
Ligne 59: Ligne 63:
             for elm in json_load:             for elm in json_load:
                 recursiv_if_json_list                 recursiv_if_json_list
 +
  
 def write(k, v): def write(k, v):
     with open(args.o, "a") as csv_file:     with open(args.o, "a") as csv_file:
-        print(quote_string(k), quote_string(v), sep=';', file=csv_file, flush=True)+        print(quote_string(k), quote_string(v), sep=";", file=csv_file, flush=True) 
  
 def truncate(): def truncate():
     with open(args.o, "a+") as csv_file:     with open(args.o, "a+") as csv_file:
         csv_file.truncate(0)         csv_file.truncate(0)
 +
  
 def main(): def main():
Ligne 73: Ligne 80:
         convert_json2csv()         convert_json2csv()
         sys.exit(0)         sys.exit(0)
-  + 
- +
 if __name__ == "__main__": if __name__ == "__main__":
     main()     main()
- 
 ~~~ ~~~
  
Ligne 95: Ligne 101:
 `json2csv_list_of_dicts.py` `json2csv_list_of_dicts.py`
 ~~~python ~~~python
-#! /usr/bin/env python3 +#!/usr/bin/env python3 
- +
 import sys import sys
 import json import json
 import argparse import argparse
 from datetime import datetime from datetime import datetime
-  + 
-parser = argparse.ArgumentParser( +parser = argparse.ArgumentParser(epilog="""Convert JSON file to CSV.""")
-    epilog="""Convert JSON file to CSV.""")+
  
 parser.add_argument("-i", help="Input JSON file") parser.add_argument("-i", help="Input JSON file")
-parser.add_argument("-o", help="Output XLS file")+parser.add_argument("-o", help="Output CSV file")
 args = parser.parse_args() args = parser.parse_args()
- + 
 def clean_field(field): def clean_field(field):
     """     """
-    Clean each fields. +    Clean each fields.
     CSV use ';' as field separator and so all ';' characters must be removed     CSV use ';' as field separator and so all ';' characters must be removed
     CSV use line break as line separator and so all '\n' and '\r' characters must be replaced     CSV use line break as line separator and so all '\n' and '\r' characters must be replaced
Ligne 120: Ligne 126:
         ret = str(field).strip().replace(";", "").replace("\n", ",").replace("\r", ",")         ret = str(field).strip().replace(";", "").replace("\n", ",").replace("\r", ",")
     return ret     return ret
 +
  
 def quote_string(thing): def quote_string(thing):
Ligne 126: Ligne 133:
     else:     else:
         return thing         return thing
 +
 +
 +def get_date_time(utimestamp):
 +    ts = datetime.fromtimestamp(utimestamp // 1000000)
 +    return ts.date(), ts.time()
 +
  
 def convert_json2csv(): def convert_json2csv():
Ligne 131: Ligne 144:
         json_load = json.load(json_file)         json_load = json.load(json_file)
     with open(args.o, "a+") as csv_file:     with open(args.o, "a+") as csv_file:
-        headers = json_load[0] +        headers = json_load[0].copy() 
-        print(';'.join(headers), file=csv_file, flush=True)+        headers["time_date"], headers["time_time"] = None, None 
 +        del headers["time_usec"] 
 +        print(";".join(headers), file=csv_file, flush=True)
         for elm in json_load:         for elm in json_load:
-          newtime = elm['time_usec'] / 1000000 +            elm["time_date"], elm["time_time"] = get_date_time(elm["time_usec"]) 
-          newtime = datetime.fromtimestamp(newtime) +            del elm["time_usec"] 
-          elm['time_usec'] = newtime +            for v in elm.values(): 
-          for v in elm.values(): +                print(quote_string(clean_field(v)), end=";", file=csv_file, flush=True) 
-            print(quote_string(clean_field(v)), end=';', file=csv_file, flush=True) +            print(file=csv_file, flush=True) 
-          print(file=csv_file, flush=True)+
  
 def truncate(): def truncate():
     with open(args.o, "a+") as csv_file:     with open(args.o, "a+") as csv_file:
         csv_file.truncate(0)         csv_file.truncate(0)
 +
  
 def main(): def main():
Ligne 150: Ligne 166:
         convert_json2csv()         convert_json2csv()
         sys.exit(0)         sys.exit(0)
-  + 
- +
 if __name__ == "__main__": if __name__ == "__main__":
     main()     main()
Ligne 166: Ligne 182:
 Bon, il y avait plus simple Bon, il y avait plus simple
 ~~~bash ~~~bash
 +# cat Historique.json | jq -r '."Browser History".[0] | keys | @csv'
 echo '"favicon_url","page_transition_qualifier","title","url","time_usec","client_id"' > Historique.csv echo '"favicon_url","page_transition_qualifier","title","url","time_usec","client_id"' > Historique.csv
  
tech/script_python_conversion_json_vers_csv.1794089233.txt.gz · Dernière modification : de Jean-Baptiste

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki