<aside> <img src="/icons/list-indent_blue.svg" alt="/icons/list-indent_blue.svg" width="40px" /> Table des matières

<aside> <img src="/icons/chat_blue.svg" alt="/icons/chat_blue.svg" width="40px" /> 📢 Français

📢 English

</aside>

</aside>

<aside> <img src="/icons/info-alternate_blue.svg" alt="/icons/info-alternate_blue.svg" width="40px" /> Articles sur les mêmes thématiques


Untitled Database

</aside>


Crédits:

Image de couverture: Aspose


Untitled

<aside> <img src="/icons/megaphone_blue.svg" alt="/icons/megaphone_blue.svg" width="40px" /> JSON est un format utilisable dans de nombreux outils, il peut donc être intéressant d’obtenir un tel type de fichier depuis un export de sa base Gramps. Gramps lui fournit des fichiers XML, il est donc nécessaire de réaliser la conversion d’un type à l’autre.

</aside>

Ci-dessous, deux programmes Python (à exécuter sur son ordinateur et non dans Gramps) pour être en mesure d’avoir un fichier JSON qu’on puisse importer dans d’autres applications.

A préalable, il faut extraire tout ou partie de sa base de donnée dans un fichier Gramps non compressé (ou si il a été compressé, il faut le décompresser et récupérer son contenu). Le fichier XML Gramps est alors celui qui entre en entrée du programme xml2json.py ci-dessous.

Avant de le lancer, positionnez deux variables d’environnement: X2J_XML et X2J_JSON contenant respectivement le nom du fichier XML qui vient d’être extrait de Gramps en entrée et le nom du fichier JSON qui sera obtenu en sortie. Il n’y a plus alors qu’à lancer le programme depuis un terminal (exemples en CMD ou Powershell):

<aside> <img src="/icons/shell_purple.svg" alt="/icons/shell_purple.svg" width="40px" /> C:\repertoire\> SET X2J_XML=”votre_fichier.gramps”

C:\repertoire\> SET X2J_JSON=”futur_fichier.json”

C:\repertoire\> python xml2json.py

</aside>

<aside> <img src="/icons/shell_purple.svg" alt="/icons/shell_purple.svg" width="40px" /> PS> Set-Item -Path env:X2J_XML -Value ”votre_fichier.gramps”

PS> Set-Item -Path env:X2J_JSON -Value ”futur_fichier.json”

PS> python xml2json.py

</aside>

  1. Première passe: Transformation de l’ensemble du contenu du fichier XML de Gramps en fichier JSON

    # Program to convert an xml file to json file
    
    # Prerequisit:
    # - Environment variables (Windows CMD: SET varname varvalue or Windows PowerShell: Set-Item -Path env:varname -Value varvalue)
    #   - X2J_XML  : XML input file [path and] name
    #   - X2J_JSON : JSON output file [path and] name
    
    import os
    import json
    import xmltodict
     
    input_file = os.environ['X2J_XML']
    output_file = os.environ['X2J_JSON']
    
    # open the input xml file and read data in form of python dictionary using xmltodict module
    with open(input_file, encoding='utf-8', mode='r') as xml_file:
        data_dict = xmltodict.parse(xml_file.read(), attr_prefix='', cdata_key='text')
         
    # generate the object using json.dumps()
    # corresponding to json data
     
    json_data = json.dumps(data_dict)
     
    # Write the json data to output
    # json file
    with open(output_file, encoding='utf-8', mode="w") as json_file:
        json_file.write(json_data)
    

    A la fin de cette passe, positionnez une troisième variables d’environnement FILT_JSON afin d’indiquer le nom du fichier JSON de sortie du second programme et lancez la seconde passe:

    <aside> <img src="/icons/shell_purple.svg" alt="/icons/shell_purple.svg" width="40px" /> C:\repertoire\> SET FILT_JSON=”futur_second_fichier.json” C:\repertoire\> python filt_json.py

    </aside>

    <aside> <img src="/icons/shell_purple.svg" alt="/icons/shell_purple.svg" width="40px" /> PS> Set-Item -Path env:FILT_JSON -Value ”futur_second_fichier.json”

    PS> python filt_json.py

    </aside>

  2. Seconde passe: Filtrage du fichier JSON pour le rendre générique

    # Program to remove headers, name formats, tags, bookmarks, namemaps from a jsonified Gramps file 
    # Remaining objects are listed in REMAINING_KEYS constants
    
    # Prerequisit:
    # - Environment variables (CMD: SET varname varvalue or PowerShell: Set-Item -Path env:varname -Value varvalue)
    #   - X2J_JSON  : input file [path and] name
    #   - FILT_JSON : output file [path and] name
    
    import os
    import json
    
    # REMAINING_KEYS definitions
    REMAINING_KEYS = "remaining keys"
    JSON_KEYS = "json keys"
    EVENTS = {
        REMAINING_KEYS: ["id", "type", "description", "noteref", "citationref", "objref", "place", "datespan", "daterange", "dateval"],
        JSON_KEYS: {"top": "database", "middle": "events", "end": "event"},
    }
    PEOPLE = {
        REMAINING_KEYS: ["id", "gender", "name", "noteref", "citationref", "objref", "eventref", "childof", "parentin", "personref"],
        JSON_KEYS : {"top": "database", "middle": "people", "end": "person"},
    }
    FAMILIES = {
        REMAINING_KEYS: ["id", "rel", "father", "mother", "noteref", "citationref", "objref", "eventref", "childref"],
        JSON_KEYS: {"top": "database", "middle": "families", "end": "family"},
    }
    CITATIONS = {
        REMAINING_KEYS: ["id", "datespan", "daterange", "dateval", "page", "confidence", "noteref", "sourceref", "objref"],
        JSON_KEYS: {"top": "database", "middle": "citations", "end": "citation"},
    }
    SOURCES = {
        REMAINING_KEYS: ["id", "stitle", "sauthor", "reporef", "spubinfo", "confidence", "noteref", "sourceref", "objref", "sabbrev"],
        JSON_KEYS: {"top": "database", "middle": "sources", "end": "source"},
    }
    PLACES = {
        REMAINING_KEYS: ["id", "type", "pname", "coord", "placeref", "noteref", "citationref", "objref", "code"],
        JSON_KEYS: {"top": "database", "middle": "places", "end": "placeobj"},
    }
    OBJECTS = {
        REMAINING_KEYS: ["id", "file", "datespan", "daterange", "dateval", "noteref", "citationref"],
        JSON_KEYS: {"top": "database", "middle": "objects", "end": "object"},
    }
    REPOSITORIES = {
        REMAINING_KEYS: ["id", "rname", "type"],
        JSON_KEYS: {"top": "database", "middle": "repositories", "end": "repository"},
    }
    NOTES = {
        REMAINING_KEYS: ["id", "type", "text"],
        JSON_KEYS: {"top": "database", "middle": "notes", "end": "note"},
    }
    DATABASE_OBJECTS = [NOTES, REPOSITORIES, SOURCES, CITATIONS, OBJECTS, PLACES, EVENTS, PEOPLE, FAMILIES]
    
    input_file = os.environ['X2J_JSON']
    output_file = os.environ['EXP_JSON']
    
    with open(input_file, encoding='utf-8', mode="r") as json_file:
        json_data = json.load(json_file)
    
    # Dict and List comprehensions to filter and convert json_data
    new_database = {
        objet[JSON_KEYS]["middle"] : [
            {
                dict_entries["handle"] : [
                    {key: value}
                    for key, value in dict_entries.items()
                    if key in objet[REMAINING_KEYS]
                ],
            }
            for dict_entries in json_data[objet[JSON_KEYS]["top"]][objet[JSON_KEYS]["middle"]][objet[JSON_KEYS]["end"]]
        ]
        for objet in DATABASE_OBJECTS
    }
    
    # Write the json data to output json file
    json_data = json.dumps(new_database)
    with open(output_file, encoding='utf-8', mode="w") as json_file:
        json_file.write(json_data)
    

Le fichier FILT_JSON peut alors être utilisé dans d’autres applications.



<aside> <img src="/icons/arrow-turn-left_blue.svg" alt="/icons/arrow-turn-left_blue.svg" width="40px" /> Retour au blog Ma généalogie avec Gramps

</aside>

<aside> <img src="/icons/info-alternate_blue.svg" alt="/icons/info-alternate_blue.svg" width="40px" /> Et pour en savoir plus


Ma généalogie avec Gramps

Gramps. Présentation

Mon Gramps

</aside>

<aside> <img src="/icons/shuffle_blue.svg" alt="/icons/shuffle_blue.svg" width="40px" /> Une page au hasard


Untitled Database

</aside>

<aside> <img src="/icons/info-alternate_blue.svg" alt="/icons/info-alternate_blue.svg" width="40px" /> Publications de cet article


</aside>

âš™