user3756607
user3756607

Reputation: 15

Issue with Parsing a Json Array

I am trying to Parse a Json array, A sample of the array i get is below with my code.

I can not seem to workout what my issue is, please forgive my question if I have included too much

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

map = "[{'network' : 'networkA','ycoord' : '73','zcoord' : '-2612','xcoord' : '-4461','owner' : 'PlayerA','name' : 'PlaceA'}, {'network' : 'NetworkB','ycoord' : '66','zcoord' : '-1915','xcoord' : '1156','owner' : 'PlayerB','name' : 'PlaceB'}, {'network' : 'NetWorkB','ycoord' : '71','zcoord' : '3091','xcoord' : '4541','owner' : 'PlayerB','name' : 'PlaceC'}, {'network' : 'NetworkB','ycoord' : '118','zcoord' : '-66','xcoord' : '5','owner' : 'PlayerB','name' : 'PlaceD'}, {'network' : 'networkA','ycoord' : '71','zcoord' : '761','xcoord' : '-248','owner' : 'PlayerA','name' : 'PlaceE'}]"
data = json.load(map)
for item in data:
    print "Network : "+ str(item['network'])
    print "Name    : "+ str(item['name'])
    print "Owner   : "+ str(item['owner'])
    print "Co ords : ("+ str(item['ycoord']+", "+ str(item['xcoord']+", "+ str(item['Zcoord']+")"

I get The error

  File "test.py", line 8, in <module>
    data = json.load(map)
  File "/usr/lib/python2.7/json/__init__.py", line 274, in load
    return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

Readable Json Data (because I know what's in the code isn't)

[{
  'network' : 'networkA',
  'ycoord' : '73',
  'zcoord' : '-2612',
  'xcoord' : '-4461',
  'owner' : 'PlayerA',
  'name' : 'PlaceA'
}, {
  'network' : 'NetworkB',
  'ycoord' : '66',
  'zcoord' : '-1915',
  'xcoord' : '1156',
  'owner' : 'PlayerB',
  'name' : 'PlaceB'
}, {
  'network' : 'NetWorkB',
  'ycoord' : '71',
  'zcoord' : '3091',
  'xcoord' : '4541',
  'owner' : 'PlayerB',
  'name' : 'PlaceC'
}, {
  'network' : 'NetworkB',
  'ycoord' : '118',
  'zcoord' : '-66',
  'xcoord' : '5',
  'owner' : 'PlayerB',
  'name' : 'PlaceD'
}, {
  'network' : 'networkA',
  'ycoord' : '71',
  'zcoord' : '761',
  'xcoord' : '-248',
  'owner' : 'PlayerA',
  'name' : 'PlaceE'
}]

Upvotes: 0

Views: 48

Answers (2)

Akshay Patil
Akshay Patil

Reputation: 970

json.load() function will require filename as a parameter. In your case, You don't want filename but an actual JSON array. Use json.loads() instead of json.load()

Also, remember The functions with an s take string parameters. The others take file streams. This applies to json.dump() and json.dumps() too.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249652

You want loads() instead of load(). Read the documentation, load() takes a filename, loads() takes actual JSON data.

Upvotes: 3

Related Questions