0

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:
  # ?
3
  • 2
    Please tell a bit more about how the codes.txt looks and how the data is present in it Commented Mar 4, 2022 at 16:19
  • 1
    We need to see the input lines. Also, you don’t create a JSON array in Python (or even JavaScript). In Python you create a dict, like you showed, and when you’re ready to save it disk, or share it, you give that dict a JSON serializer which creates the JSON (and can also save it to disk). Commented Mar 4, 2022 at 16:25
  • What you've described isn't valid JSON. Are you sure you're working with JSON? Commented Mar 4, 2022 at 16:25

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

You seem to be pretty sure that this code will work. What contents of 'code.txt' did you try this with and what does value does data_json have?
you're right, it was incorrect, my bad. I fixed it and provided the example used for codes.txt
I receive this error whenever I try it: 'TypeError: the JSON object must be str, bytes or bytearray, not dict'
Before my edit the last line was executing json.loads, which is the opposite operation (it loads a json string as a dict). This leads to the error you just reported
Oh wait, I didn't realise you changed loads to dumps, nevermind. It worked perfectly, thanks!
0

This should be enough:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.