0

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?

2 Answers 2

2

Try with this

import json

with open('strings.json') as json_data:
 d = json.load(json_data)
 print(d)
Sign up to request clarification or add additional context in comments.

2 Comments

The result is: ValueError: Expecting property name: line 1 column 2 (char 1)
You may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.