Skip to content
New: 17 free file converters that never upload your files
File Converter Guides

How to Convert TXT to JSON: Lists, Key-Value Pairs and Tables Without Errors

How to convert TXT to JSON: pick the right structure, use our free browser converter, Python, Node or jq, then validate and fix common errors.

How to convert TXT to JSON: LeadCanal guide cover
On this page
  1. What JSON structure do you need before you convert?
  2. How to convert TXT to JSON with our free browser tool
  3. How do you convert a text file to JSON in Python?
  4. How to change TXT to JSON with JavaScript or Node.js
  5. Converting text to JSON on the command line with jq and PowerShell
  6. Can Excel or Power Query turn TXT into JSON?
  7. Can you just rename a .txt file to .json?
  8. Which TXT to JSON method should you use?
  9. How do you validate JSON after converting?
  10. JSON rules worth knowing before you convert
  11. Common TXT to JSON errors and how to fix them
  12. Why a browser-based converter matters for private files
  13. Frequently asked questions
  14. Conclusion: key takeaways
  15. Editorial policy
  16. Content transparency
  17. About the author

If you want to know how to convert TXT to JSON, the short answer is this: decide what shape the JSON should take (a list of lines, one key-value object, or an array of objects from a table), then let a converter or a few lines of code build it. The fastest route is our free TXT to JSON converter, which reads your text in the browser, detects the layout and gives you valid JSON to copy or download. If you prefer code, Python’s built-in json module, Node.js and jq all do the job in a handful of lines.

We handle text exports every day at LeadCanal: lead lists pasted from spreadsheets, CRM dumps, tab-separated reports and contact files. Below is how to convert TXT to JSON with the methods we actually use, plus the errors that break JSON most often.

Quick answer: To turn a .txt file into JSON:

  • Fastest: drop the file into the free text to JSON tool, keep “Detect automatically” on, then copy or download the .json file. Nothing is uploaded.
  • Python: read the lines, build a list or dict, and save it with json.dump().
  • Command line: jq -nR '[inputs]' input.txt turns every line into an item in a JSON array.
  • Always: validate the result before you import it anywhere.

Free LeadCanal tools for this guide

Check and fix it yourself in a few seconds, no signup needed.

TXT to JSON →TXT to CSV →CSV splitter →Email extractor →

What JSON structure do you need before you convert?

A .txt file has no structure of its own, so the first job is choosing which of three common shapes your data should become.

  • Array of lines: a plain list, one value per line. Good for keyword lists, email lists, URLs or tags.
  • Key-value object: lines such as name: Ana become {"name": "Ana"}. Good for settings files and single records.
  • Array of objects: a table with a header row, where each row becomes an object and the headers become keys. Good for lead lists, product feeds and exports.
Text you have JSON you get Typical use
apple / banana / cherry, one per line ["apple", "banana", "cherry"] Lists, tags, keywords
name: Ana / age: 31 / active: true {"name": "Ana", "age": 31, "active": true} Config, one record
Blocks of key: value lines separated by blank lines An array with one object per block Notes, profiles, log entries
name,email header, then rows [{"name": "Ana", "email": "ana@example.com"}] Lead lists, CRM and API imports

If the target is an API or app import, check its documentation first. Most expect an array of objects with specific key names.

How to convert TXT to JSON with our free browser tool

We built the LeadCanal TXT to JSON converter because we kept writing throwaway scripts for the same three shapes.

  1. Open the converter and paste your text, or drop one or more .txt, .csv, .tsv or .log files.
  2. Leave “Read the text as” on Detect automatically, or force a mode: a list of lines, key: value pairs, or a table with a header row.
  3. Pick the indentation: 2 spaces, 4 spaces, tabs or minified.
  4. Keep “Turn numbers, true/false and null into JSON types” ticked if you want real numbers and booleans instead of strings.
  5. Click Convert to JSON, check the summary line (it tells you how the text was read and how many items it produced), then copy or download the .json file.

How does the auto-detection decide?

The detector checks your text in this order:

  • Already JSON: text that parses as JSON is simply reformatted. One JSON object per line (NDJSON or JSON Lines) becomes a single array.
  • Table: if the lines share a tab, comma, semicolon or pipe separator, the first row becomes the keys and every other row becomes an object.
  • Key-value pairs: if most lines look like key: value or key=value, you get an object. Blank lines between blocks give you an array of objects, and a repeated key turns into an array.
  • Lines: anything else becomes a plain array of strings, with empty lines skipped.

Two details protect your data. ZIP codes and IDs with a leading zero, such as 02134, stay as text, and so do numbers longer than 15 digits, so nothing is silently rounded. Empty header cells get names like column_1 so every value keeps a key.

A worked example from our own workflow

A typical case for us: a client sends a tab-separated .txt export of contacts with columns for name, company, email and ZIP code, and the destination CRM accepts JSON through its API. We drop the file into the converter. It reads the file as table rows, uses the header as keys, and keeps the ZIP column as strings, so “02134” does not become 2134.

The CRM limits how many records it accepts per request, so for a large file we first run the table through the CSV splitter to cut it into equal parts, then convert each part. If the export arrives as messy text with odd separators, we clean it into columns with the TXT to CSV converter before turning it into JSON.

How do you convert a text file to JSON in Python?

If you are working out how to convert TXT to JSON in code, start here. Python ships with a json module in the standard library, so you need nothing extra. Here are the three shapes.

1. Array of lines

import json

with open("input.txt", encoding="utf-8") as f:
    lines = [line.strip() for line in f if line.strip()]

with open("output.json", "w", encoding="utf-8") as f:
    json.dump(lines, f, indent=2, ensure_ascii=False)

2. Key-value object

import json

data = {}
with open("config.txt", encoding="utf-8") as f:
    for line in f:
        if ":" in line:
            key, value = line.split(":", 1)
            data[key.strip()] = value.strip()

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Splitting with split(":", 1) matters: it splits only on the first colon, so values like times or URLs stay whole.

3. Array of objects from a table

import csv, json

with open("leads.txt", encoding="utf-8-sig", newline="") as f:
    rows = list(csv.DictReader(f, delimiter="\t"))

with open("leads.json", "w", encoding="utf-8") as f:
    json.dump(rows, f, indent=2, ensure_ascii=False)

Change delimiter to ",", ";" or "|" to match your file. The utf-8-sig encoding quietly removes a byte order mark, which otherwise ends up glued to your first key. Note that csv.DictReader keeps every value as a string, which is safe for ZIP codes and phone numbers.

How to change TXT to JSON with JavaScript or Node.js

In Node.js, read the file, split it into lines and serialise it with JSON.stringify:

const fs = require("fs");

const lines = fs.readFileSync("input.txt", "utf8")
  .split(/\r?\n/)
  .map(l => l.trim())
  .filter(Boolean);

fs.writeFileSync("output.json", JSON.stringify(lines, null, 2));

The /\r?\n/ pattern handles both Windows and Unix line endings. For key-value lines, split each line on the first colon and build an object, exactly as in the Python version. Going the other way, JSON.parse throws a SyntaxError on invalid input, which makes it a quick validity check (see the MDN reference for JSON.parse).

Converting text to JSON on the command line with jq and PowerShell

jq is a small command-line JSON processor for Linux, macOS and Windows. Two commands cover most cases:

# Every line becomes a string in one array
jq -nR '[inputs]' input.txt > output.json

# Drop empty lines too
jq -nR '[inputs | select(length > 0)]' input.txt > output.json

# "key: value" lines become one object
jq -nR '[inputs | select(length > 0) | capture("^(?<key>[^:]+):\\s*(?<value>.*)$")] | from_entries' config.txt > config.json

On Windows, PowerShell can do it without installing anything. For a tab-separated table:

Import-Csv leads.txt -Delimiter "`t" | ConvertTo-Json | Set-Content leads.json -Encoding utf8

For a plain list of lines:

$lines = (Get-Content input.txt -Raw) -split "\r?\n" | Where-Object { $_ -ne "" }
ConvertTo-Json -InputObject @($lines) | Set-Content output.json -Encoding utf8

Wrapping the lines in @() keeps the output an array even when the file has a single line.

Can Excel or Power Query turn TXT into JSON?

Excel can read JSON through Power Query, but it has no built-in “save as JSON” option. It is still useful as a cleaning step:

  1. Import the text file with Data, then From Text/CSV, and choose the right delimiter.
  2. Use Power Query to split columns, trim spaces, remove duplicates and rename headers to the keys you need.
  3. Load the result to a sheet and save it as CSV (UTF-8).
  4. Drop that CSV into the txt to json tool to get an array of objects.

Watch the ZIP and phone columns in Excel. It drops leading zeros when it treats a column as numbers, so set those columns to Text during import.

Can you just rename a .txt file to .json?

Only if the text inside is already valid JSON. Renaming changes the extension, not the content. If your file already holds JSON, show file extensions (in Windows 11 File Explorer: View, then Show, then File name extensions; in Windows 10: the View tab, then File name extensions; on a Mac: Get Info, then Name & Extension) and rename it. Otherwise, convert it with one of the methods above.

Which TXT to JSON method should you use?

Method Cost Upload needed? Best for
LeadCanal browser converter Free No, runs in your browser Quick one-off files, non-coders, private data
Python json module Free No Repeatable jobs, custom rules, large files
Node.js Free No JavaScript projects and build scripts
jq Free No Shell pipelines, Linux and macOS servers
PowerShell Free, built into Windows No Windows users with no extra installs
Excel and Power Query Paid Microsoft 365 or Office No Cleaning messy tables before converting
Upload-based online converters Usually free tier Yes, file goes to a server Non-sensitive files only

How do you validate JSON after converting?

Never import JSON you have not checked. Any of these will tell you if it parses:

  • Python: python -m json.tool output.json prints the formatted JSON or the line and column of the first error.
  • jq: jq . output.json fails with an error message if the file is invalid.
  • VS Code: open the .json file and syntax errors are underlined.
  • Our converter: the output is built and checked by the browser’s own JSON engine before you see it.

Valid is not the same as correct. Spot-check the first and last records, the item count and tricky fields such as ZIP codes and dates.

JSON rules worth knowing before you convert

Rule What it means
Strings use double quotes "name" is valid, 'name' is not
No trailing commas [1, 2,] is invalid
No comments // and /* */ are not allowed
Numbers have no leading zeros 02134 must be stored as the string "02134"
Safe integer limit in JavaScript Integers above 9,007,199,254,740,991 lose precision, so long IDs should be strings
Encoding JSON exchanged between systems must be UTF-8 (RFC 8259)
Escapes inside strings Quotes become \", backslashes become \\, tabs \t, new lines \n

The full grammar is short and readable in RFC 8259, the JSON standard.

Common TXT to JSON errors and how to fix them

Error or symptom Cause Fix
“Expecting property name” or “Unexpected token ]” Trailing comma after the last item Remove the comma, or generate JSON with a serializer instead of by hand
“Unexpected token ‘” Single quotes around keys or values Use double quotes; let json.dump or JSON.stringify write them
Broken strings around Windows paths Unescaped backslashes, as in C:\new Escape them as \\; serializers do this for you
Strange characters like é or a symbol before the first key File saved in another encoding, or a byte order mark Re-save as UTF-8; read with utf-8-sig in Python
ZIP 02134 shows as 2134 Leading zeros parsed as a number Keep the field as a string
Long IDs end in 000 Integer beyond JavaScript’s safe range Store IDs as strings
Everything lands in one field Wrong delimiter detected or set Force the right separator, or clean the text into columns first
“\r” at the end of every value Windows line endings split on \n only Split on \r?\n or strip each line

The pattern behind most of these is the same: build JSON with a serializer, never by gluing strings together. Every method in this guide does that.

Why a browser-based converter matters for private files

Text files are rarely harmless. Ours contain names, work emails and phone numbers, and log files often hold API keys or tokens. Many online converters upload your file to their server, and you cannot see what happens to it there.

Our converter runs entirely in your browser, so the file is never uploaded and nothing is stored on our servers. Close the tab and it is gone. Each tool also checks the file type and its first bytes before opening it, so a renamed program is refused. And if your text hides contact details you need to pull out first, the email extractor works the same local way.

Once your data is in JSON, it often heads to an API. If that API checks email addresses, our guide to validating emails in real time with an API shows how those responses look. You can find every converter we have built on our free tools page.

Frequently asked questions

How to convert TXT to JSON for free?

Use a free browser tool such as the LeadCanal converter, or write a few lines with Python’s json module, Node.js, jq or PowerShell. All of these are free and none needs your file uploaded.

Can you convert TXT to JSON online without uploading the file?

Yes. A converter that runs in the browser processes the text on your own device. Ours works this way, so the file never reaches a server.

How do I convert a TXT file to JSON in Python?

Read the file with open(), build a list, dict or list of dicts, and save it with json.dump(data, f, indent=2). Use csv.DictReader for tables with a header row.

How do I change TXT to JSON in Windows 11?

If the text is already valid JSON, turn on file name extensions in File Explorer and rename the file. If not, convert it with PowerShell’s ConvertTo-Json or a browser converter.

Is a JSON file just a text file?

Yes, JSON is plain UTF-8 text that follows strict rules. Any text editor can open it, but only text that follows the JSON grammar will parse.

Why does my converted JSON show numbers as strings?

Some methods, such as Python’s csv module, read every value as text. Convert specific fields yourself, or use a tool that types numbers and booleans while keeping leading-zero values as strings.

Conclusion: key takeaways

Knowing how to convert TXT to JSON is mostly a structure decision. Pick the shape, convert with a serializer, and validate before you import.

  • Decide first: array of lines, key-value object, or array of objects from a table.
  • For quick, private files, use a browser converter that detects the layout for you.
  • For repeat jobs, Python’s json module, Node.js or jq do it in a few lines.
  • Keep ZIP codes, phone numbers and long IDs as strings so nothing is lost.
  • Validate with python -m json.tool or jq, then spot-check a few records.

Key takeaways

How to convert TXT to JSON

1 Decide first: array of lines, key-value object, or array of objects from a table.
2 For quick, private files, use a browser converter that detects the layout for you.
3 For repeat jobs, Python's json module, Node.js or jq do it in a few lines.
4 Keep ZIP codes, phone numbers and long IDs as strings so nothing is lost.
5 Validate with python -m json.tool or jq, then spot-check a few records.

Editorial policy

We write about tasks we do ourselves. Every method in this guide was checked against official documentation, and the code samples were written to run as shown with standard tools. We update guides when tools or versions change, and we do not accept payment to include or rank any product.

Content transparency

This guide was researched with keyword and search data to cover the questions people ask about how to convert TXT to JSON, and checked against the Python, MDN, jq and RFC 8259 documentation. LeadCanal built and offers the free browser-based converters mentioned here. They are free to use with no sign-up.

About the author

This guide was written by the LeadCanal team. We build verified B2B lead lists, enrich CRM data and run cold email infrastructure every day, which means we convert, clean and split CSV, TXT, VCF and JSON files for clients constantly. We built our free file converters to handle that work without uploading anyone’s data.

Found this useful? Share it with your team.

Written by LeadCanal

The LeadCanal team builds verified B2B lists and runs cold email infrastructure for agencies and sales teams. Every guide comes from campaigns we send every day.

Done-for-you lead generation

Want this done for you?

Targeted lists and cold email campaigns that book qualified meetings.