简体   繁体   中英

Loading json data from file in python

I was saving data from a webpage with the following code:

[...]
response = urllib2.urlopen(req)
the_page = response.read()
data_to_analyse = json.loads(the_page)
import datetime
datafile = open(str(datetime.datetime.now())+'_data.json','w')
datafile.write(str(data_to_analyse))
[...]

Now I try to work with data saved in datafile, but I can't handle the json correct.

datafile start example part :

{
    u'SiteRep': {
                  u'DV': {
                           u'type': u'Obs', 
                           u'dataDate': u'2016-11-18T10:00:00Z', 
                           u'Location': [
                                            {
                                                u'elevation': u'15.0',
                                                u'name': u'BALTASOUND',
                                                u'i': u'3002'
[and so on - file closes correct...]

Before I could simple process 'data_to_analyse' with:

for SiteRep in data_to_analyse:
    for data_to_analyse_experience in data_to_analyse[SiteRep]:

and everything worked. Now I receive the error:

**TypeError:** string indices must be integers, not str

if i try to load the data from the file with that code:

for datafile in os.listdir('.'):
    if datafile.endswith('.json'):
        data = open(datafile,'r').read()

        jsondata = json.dumps(data)

or:

**ValueError:** Expecting property name: line 1 column 2 (char 1)

with:

        jsondata = json.loads(data)

How to convert the file into a correct json object?

Try with this

import json

with open('strings.json') as json_data:
 d = json.load(json_data)
 print(d)

Actually JSON ValueError: Expecting property name: line 1 column 2 (char 1) solved the problem by:

    data_to_analyse = open(datafile,'r').read()
    data_to_analyse = data_to_analyse.replace("'",'"')
    data_to_analyse = data_to_analyse.replace("u\"",'"')
    jsondata = json.loads(data_to_analyse)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM