skip to Main Content

I have a json file like this:

"["SOMEURL","SOMEURL","SOMEURL","SOMEURL"]"

and I need to put these values to the array

but such code as

fileObject = open("doc_1.json", "r")
jsonContent = fileObject.read()
aList = json.loads(jsonContent)
print(aList)

opens it as a simple string, so I can’t take any element of the list above.
Any clues I found on internet fit only for JSON files with complex structure, with dictionaries and so on, but it’s not the case. How do I read it?

2

Answers


  1. To read the JSON data you have into a Python list, you need to ensure that your JSON data is properly formatted. In your provided JSON data, it seems there are issues with the quotes and escape characters. Here’s the corrected JSON data:

    ["SOMEURL","SOMEURL","SOMEURL","SOMEURL"]
    

    Once you have your JSON data in this format, you can use the code you provided to read it into a Python list:

    import json
    
    fileObject = open("doc_1.json", "r")
    jsonContent = fileObject.read()
    aList = json.loads(jsonContent)
    fileObject.close()  # Close the file when you're done with it
    
    print(aList)
    

    This code will read the JSON data from "doc_1.json" and convert it into a Python list. Make sure the JSON data in your file is without extra quotes and escape characters.

    Login or Signup to reply.
  2. I’m assuming you have double encoded json string:

    import json
    
    with open("your_file.json", "r") as f_in:
        data = json.load(f_in)
    
    print(data, type(data))
    
    data = json.loads(data)
    print(data, type(data))  # data is of type `list`
    

    Prints:

    ["SOMEURL","SOMEURL","SOMEURL","SOMEURL"] <class 'str'>
    ['SOMEURL', 'SOMEURL', 'SOMEURL', 'SOMEURL'] <class 'list'>
    

    Content of your_file.json:

    "["SOMEURL","SOMEURL","SOMEURL","SOMEURL"]"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search