Python 3: How to read file json into list of dictionary?
<p>I have file with Json format:</p>

<pre><code>{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
</code></pre>

<p>When i use following code, it show an error:</p>

<pre><code>    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)

with open('E:/list.txt','r') as target:
        my_list = json.load(target)
</code></pre>

<p>How to convert content of my file into list of dictionary ? Thank you  </p>

<p>It's not loading your content basically because it's not a valid json format, try this script:</p>

<pre><code>import json

try:
    file_content = """{"uid": 2, "user": 1}
    {"uid": 2, "user": 1}
    {"uid": 2, "user": 1}"""

    json.loads(file)
except Exception as e:
    print("This is not JSON!")

print('-' * 80)
file_content = """[{"uid": 2, "user": 1},
{"uid": 2, "user": 1},
{"uid": 2, "user": 1}]"""

print(json.loads(file_content))
</code></pre>

<p>The result will be:</p>

<pre><code>This is not JSON!
--------------------------------------------------------------------------------
[{'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}]
</code></pre>

<p>Proving that if if you wrap your dictionary into brackets and separate the items with commas the json will be parsed correctly</p>

<p>Of course, If you don't want to tweak your file at all, you can do something like this to create your output:</p>

<pre><code>import json

file_content = """{"uid": 2, "user": 1}


{"uid": 2, "user": 1}


{"uid": 2, "user": 1}

"""

output = [json.loads(line)
          for line in file_content.split("\n") if line.strip() != ""]
print(output)
</code></pre>

python json dictionary