DEV Community

Gavi Narra
Gavi Narra

Posted on

Convert ChatGPT conversations to Obsidian (Markdown format)

I am usually asking ChatGPT the same questions and would like to store and index my chat history in Obsidian. First thing you need to do is to download your conversations. Follow the instructions here

https://help.openai.com/en/articles/7260999-how-do-i-export-my-chatgpt-history-and-data

Once you have done this, you will find a folder with your conversations and there is a json file with the data.

The following python script reads this json file and creates the each conversation as an output markdown file that you can just import to Obsidian

import json
import os
def get_conversation(node_id, mapping, list):
    node = mapping[node_id]
    if 'message' in node and node['message'] is not None:
        content_parts = node['message']['content']['parts']
        if len(content_parts) > 0:
            author_role = node['message']['author']['role']
            list.append(f"## {author_role}\n {''.join(content_parts)}")

    for child_id in node.get('children', []):
        get_conversation(child_id, mapping,list)

if __name__ == '__main__':
    folder_path = "output"
    # Check if the directory exists
    if not os.path.isdir(folder_path):
        # If not, create the directory
        os.makedirs(folder_path)
    with open('conversations.json') as f:
        data = json.loads(f.read())
        for item in data:
            title = item["title"]
            title = title.replace("/","_").replace('"','')
            if title == "New chat":
                title = "New chat " + str(int(item["create_time"]))
            root_node_id = [node_id for node_id, node in item['mapping'].items() if node['parent'] is None][0]
            list = []
            get_conversation(root_node_id, item['mapping'],list)
            with open(f'{folder_path}/{title}.md','w') as outfile:
                outfile.write('\n'.join(list))

Enter fullscreen mode Exit fullscreen mode

Sometimes ChatGPT fails to create a title for your conversation and in that case, it just uses "New chat", the script above concatenates the create time epoch to make it unique.

Top comments (1)

Collapse
 
paulclip profile image
Paul Clip

Hey Gavi, thanks for posting this. Finally got 'round to uploading some fixes / enhancements compatible with the latest version of the ChatGPT json.