3

I have a file which has the same structure as python list / dictionaries, i.e.

[
    {
      "key1" : "value1",
      "key2" : "value2",
       ...
    },
    {
      "key1" : "value3",
      "key2" : "value4",
      ...
    },
    ...
]

Is there some easy way how to read this file and convert it into a list of dictionaries?

Michal
  • 671
  • 3
  • 9
  • 22

3 Answers3

13
with open('your_file', encoding='utf-8') as data_file:
   data = json.loads(data_file.read())
khelili miliana
  • 3,730
  • 2
  • 15
  • 28
2

if the file is a json file, then

import json
with open('file_url') as data_file:    
    data = json.load(data_file)
    print(data[0]['key1'])        
    print(data[0]['key2'])
hasbi
  • 520
  • 3
  • 10
1

I think you want to look into the JSON module. If that is the format of your file, of course. If not, you can write your own text parser. It'd be helpful to have more information about your use case, where the file comes from, and that kind of stuff.

Owen Hempel
  • 434
  • 2
  • 8