goblin2986
goblin2986

Reputation: 1009

Work with JSON in Python

{"required_items":[
                   {
                    "filename":"abcd",
                    "no":"3"
                   },
                   {
                    "filename":"abc",
                    "no":"2"
                   }
                  ]}

I am not getting the code of the JSON format in Python - I want to insert the filename and no through a loop.


list_of_other_ids={}
for i in xxxx:    
  entry={}
  entry['filename'] = "XXXX"
  entry['no'] =XX
  list_of_other_ids.append(entry)

I am doing like this... and it fails.

Upvotes: 1

Views: 2790

Answers (1)

leoluk
leoluk

Reputation: 12951

# data.txt

{"required_items":[
                   {
                    "filename":"abcd",
                    "no":"3"
                   },
                   {
                    "filename":"abc",
                    "no":"2"
                   }
                  ]}

# parser.py

import json 

data = json.load(open('data.txt'))

for file in data:
    print file['filename']

# This will output:
#  abcd
#  abc

If you want to append new items:

data.append({ 'filename': 'foo',
            'nr': 1 })

json.dump(data, open('data.txt', 'w'))

Upvotes: 5

Related Questions