Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert markdown table to json with python

I am trying to figure out, what is the easiest way to convert some markdown table text into json using only python. For example, consider this as input string:

| Some Title | Some Description             | Some Number |
|------------|------------------------------|-------------|
| Dark Souls | This is a fun game           | 5           |
| Bloodborne | This one is even better      | 2           |
| Sekiro     | This one is also pretty good | 110101      |

The output should be like this:

[
    {"Some Title":"Dark Souls","Some Description":"This is a fun game","Some Number":5},
    {"Some Title":"Bloodborne","Some Description":"This one is even better","Some Number":2},
    {"Some Title":"Sekiro","Some Description":"This one is also pretty good","Some Number":110101}
]

Note: Ideally, the output should be RFC 8259 compliant, aka use double quotes " instead of single quotes ' around they key value pairs.

I've seen some JS libraries that do that, but nothing for python only.

like image 276
Kyu96 Avatar asked Aug 31 '26 03:08

Kyu96


2 Answers

You could let csv do the main work and do something like the following:

import csv
import json

markdown_table = """| Some Title | Some Description             | Some Number |
|------------|------------------------------|-------------|
| Dark Souls | This is a fun game           | 5           |
| Bloodborne | This one is even better      | 2           |
| Sekiro     | This one is also pretty good | 110101      |"""

lines = markdown_table.split("\n")

dict_reader = csv.DictReader(lines, delimiter="|")
data = []
# skip first row, i.e. the row between the header and data
for row in list(dict_reader)[1:]:
    # strip spaces and ignore first empty column
    r = {k.strip(): v.strip() for k, v in row.items() if k != ""}
    data.append(r)

print(json.dumps(data, indent=4))

This is the output

[
    {
        "Some Title": "Dark Souls",
        "Some Description": "This is a fun game",
        "Some Number": "5"
    },
    {
        "Some Title": "Bloodborne",
        "Some Description": "This one is even better",
        "Some Number": "2"
    },
    {
        "Some Title": "Sekiro",
        "Some Description": "This one is also pretty good",
        "Some Number": "110101"
    }
]
like image 52
wolfrevo Avatar answered Sep 02 '26 16:09

wolfrevo


My approach was very similar to @Kuldeep Singh Sidhu's:


md_table = """
| Some Title | Some Description             | Some Number |
|------------|------------------------------|-------------|
| Dark Souls | This is a fun game           | 5           |
| Bloodborne | This one is even better      | 2           |
| Sekiro     | This one is also pretty good | 110101      |
"""

result = []

for n, line in enumerate(md_table[1:-1].split('\n')):
    data = {}
    if n == 0:
        header = [t.strip() for t in line.split('|')[1:-1]]
    if n > 1:
        values = [t.strip() for t in line.split('|')[1:-1]]
        for col, value in zip(header, values):
            data[col] = value
        result.append(data)

Result is:

[{'Some Title': 'Dark Souls',
  'Some Description': 'This is a fun game',
  'Some Number': '5'},
 {'Some Title': 'Bloodborne',
  'Some Description': 'This one is even better',
  'Some Number': '2'},
 {'Some Title': 'Sekiro',
  'Some Description': 'This one is also pretty good',
  'Some Number': '110101'}]
like image 35
mullinscr Avatar answered Sep 02 '26 15:09

mullinscr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!