Ask coding questions

← Back to all posts
can you convert a text file to a json file
DarkTheif (5)

So I am wondering If you can make a script to convert a txt file to json file like

[
  "hello"
]

I have tried this code

import json

filename = 'example.txt'

dict1 = {}

with open(filename) as fh:

	for line in fh:

		command, description = line.strip().split(None, 1)

		dict1[command] = description.strip()

out_file = open("1example.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)

out_file.close()

This being the text file

This is a example
this is a different example
this is a 3rd example

but using the python code it outputs

{
   "This": "is a example",
   "this": "is a different example",
   "this": "is a 3rd example"

  }
Comments
hotnewtop
Coder100 (16985)

we have something called readlines

file = open(filename)
a = [b.trim for b in file.readlines()]

json.dump(...)
Bookie0 (5976)

So wait you want to make everything to a single string in the json file?

DarkTheif (5)

@Bookie0 No I mean I want it like

{
   "This is a example",
   "this is a different example",
   "this is a 3rd example"
}

because I have a text file with over 400 lines and I don't want to make it a like that by hand

Coder100 (16985)

that's not what you mean, that's an object!!

[
   "This is a example",
   "this is a different example",
   "this is a 3rd example"
]

@DarkTheif

Bookie0 (5976)

@DarkTheif hm ok when you have this dict:

{
   "This": "is a example",
   "this": "is a different example",
   "this": "is a 3rd example"

  }

what about looping through it, putting in a variable the value, then adding it to the key of the name, and finally delete the value since it's already in the key name. If you're a bit stuck, I'll try to create a program or something tomorrow.

Good luck! :D

DarkTheif (5)

@Coder100 oh yea thats what I mean

Coder100 (16985)

anyways what does my idea look @DarkTheif

DarkTheif (5)

@Coder100 Well I'm Like the worst at python I don't really understand it at all I was told by a friend to try that script I know javascript a lot more but still I don't really understand anything with json files tbh I know how to read them and to right to them but that is with discord.js so doesn't really help me here