Can't access JSON loaded with json.dumps(json.loads(input))

Suppose I have json data like this.

{"id": {"$oid": "57dbv34346"}, "from": {"$oid": "57dbv34346sbgwe"}, "type": "int"}
{"id": {"$oid": "57dbv34345"}, "from": {"$oid": "57dbv34345sbgwe"}, "type": "int"}

I wrote a script like this in python

import json
with open('klinks_buildson.json', 'r') as f:
    for line in f:
        distros_dict = json.dumps(json.loads(line), sort_keys=True, indent=4)
        print distros_dict['from']
        print "\n"

But It is giving me an error:

print distros_dict['from']
TypeError: string indices must be integers, not str

I want data of the from in both the lines.

1 answer

  • answered 2018-05-16 06:25 Burhan Khalid

    You don't need to load the line, you can load the file (assuming its valid json); like this:

    with open('klinks_buildjson.json', 'r') as f:
       data = json.load(f)
    

    Now data is a list, where each item is an object. You can iterate through it:

    for row in data:
       print(row['from'])
    

    To fix your immediate problem, remove json.dumps which is used to convert an object to a string, which is not what you want here.

    distros_dict = json.loads(line)