The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Convert text files into JSON databases

To convert text files into JSON databases, the approach depends on the structure of your text files. Below are a few common scenarios and how to convert them into JSON format:


1. Plain Text (Key-Value Pairs)

Example Input (data.txt):

vbnet
name: John Doe age: 30 city: New York

Converted JSON:

json
{ "name": "John Doe", "age": 30, "city": "New York" }

Python Script:

python
import json data = {} with open('data.txt') as f: for line in f: if ':' in line: key, value = line.strip().split(':', 1) data[key.strip()] = value.strip() with open('data.json', 'w') as json_file: json.dump(data, json_file, indent=4)

2. CSV-like Structure

Example Input (data.txt):

pgsql
name,age,city John Doe,30,New York Jane Smith,25,Los Angeles

Converted JSON:

json
[ { "name": "John Doe", "age": 30, "city": "New York" }, { "name": "Jane Smith", "age": 25, "city": "Los Angeles" } ]

Python Script:

python
import csv import json with open('data.txt', newline='') as f: reader = csv.DictReader(f) rows = list(reader) with open('data.json', 'w') as json_file: json.dump(rows, json_file, indent=4)

3. Paragraph or Free-Form Text (Split by Delimiters)

Example Input:

ini
name=John Doe;age=30;city=New York name=Jane Smith;age=25;city=Los Angeles

Converted JSON:

json
[ { "name": "John Doe", "age": 30, "city": "New York" }, { "name": "Jane Smith", "age": 25, "city": "Los Angeles" } ]

Python Script:

python
import json entries = [] with open('data.txt') as f: for line in f: item = {} pairs = line.strip().split(';') for pair in pairs: if '=' in pair: key, value = pair.split('=', 1) item[key.strip()] = value.strip() entries.append(item) with open('data.json', 'w') as json_file: json.dump(entries, json_file, indent=4)

If you provide a sample of your text file’s format, I can tailor the conversion script more precisely to your case.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About