779804
779804

Reputation: 199

Creating a JSON Array in Python using contents from a file

Well, I have a list of numbers inside of a file called "codes.txt", and I'm trying to sort them into an array like this:

{
  codes: [
    "430490",
    "348327",
    "923489"
  ]
}

Or just simply ["430490", "348327", "923489"]. How would I do this? I'm not trying to output this into a file, but create a variable that contains that JSON array. I have this so far:

codefile = open('codes.txt', 'r')
codelist = logfile.readlines()
codefile.close()
for line in codelist:
  # ?

Upvotes: 0

Views: 1348

Answers (2)

jkoestinger
jkoestinger

Reputation: 1010

I think you pretty much have it correct already:

codefile = open('codes.txt', 'r')
codelist = codefile.readlines()
codefile.close()
data = {
    'codes': [code.strip() for code in codelist]
}

# This is a dict, if you need real json:

import json
data_json = json.dumps(data)

Edit: the code was wrong, it has been corrected and tried with the following content for codes.txt

430490
348327
923489

Upvotes: 1

md2perpe
md2perpe

Reputation: 3061

This should be enough:

with open('codes.txt', 'r') as codefile:
    data = {
        'codes': list(codefile)
    }

Upvotes: 0

Related Questions