0

I have a php script that outputs a json array that looks like this...

[{"year":"2016","Month":"Apr","the_days":"16, 29, 30"},
{"year":"2016","Month":"May","the_days":"13, 27"},
{"year":"2016","Month":"Jun","the_days":"10, 11, 24"},
{"year":"2016","Month":"Jul","the_days":"08, 22, 23"},
{"year":"2016","Month":"Aug","the_days":"06, 20"},
{"year":"2016","Month":"Sep","the_days":"02, 03, 16, 17, 30"},
{"year":"2016","Month":"Oct","the_days":"01, 14, 15, 29"},
{"year":"2016","Month":"Nov","the_days":"25"},
{"year":"2016","Month":"Dec","the_days":"09, 10, 23, 24"}]

I'm trying to put together some Python that will (eventually) output something like....

Apr: 16, 29, 30
May: 13, 27
//etc

...but I'm not having any luck pulling the array out. This is code that I'm using in Python3 (that I've pulled together from other Stack questions that I've searched for).

import urllib.request
import json

response = urllib.request.urlopen('http://www.captainobviousobviously.co.uk/private/Apijson.php')
content = response.read()   
data = json.load(content.decode('utf-8'))

print(data)

This is the error that I'm getting...

Traceback (most recent call last):
  File "/home/pi/Python/availableDates.py", line 6, in <module>
data = json.load(content.decode('utf-8'))
  File "/usr/lib/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

I'm not really sure how to fix it.

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
dazzathedrummer
  • 511
  • 2
  • 10
  • 26

3 Answers3

1

Replace data = json.load(content.decode('utf-8')) with data = json.loads(content.decode('utf-8'))

'load' is for files and 'loads' for strings.

Refer What is the difference between json.dumps and json.load?.

As for the code for your problem

for i in data:
    print (str(i['Month'])+":"+str(i['the_days']))
Community
  • 1
  • 1
sharpe
  • 61
  • 3
0

Use json.loads instead. load is for loading from a stream, such as a file, whereas loads loads from a string.

data = json.loads(content.decode('utf-8'))

From the Python documentation:

json.load

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

A string isn't a "file-like object", which is why you get your error - the JSON is trying to call .read on the string, but that doesn't exist.

Community
  • 1
  • 1
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
0

You need to use json.loads(<json str>). If you want you can do the following

content = response.read().decode()
data = json.loads(content)
for d in data:
    print(d["Month"], d["the_days"], sep=":")
C Panda
  • 3,297
  • 2
  • 11
  • 11