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'
}]
You want loads() instead of load(). Read the documentation, load() takes a filename, loads() takes actual JSON data.
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.
Related
I must be really slow because I spent a whole day googling and trying to write Python code to simply list the "code" values only so my output will be Service1, Service2, Service2. I have extracted json values before from complex json or dict structure. But now I must have hit a mental block.
This is my json structure.
myjson='''
{
"formatVersion" : "ABC",
"publicationDate" : "2017-10-06",
"offers" : {
"Service1" : {
"code" : "Service1",
"version" : "1a1a1a1a",
"index" : "1c1c1c1c1c1c1"
},
"Service2" : {
"code" : "Service2",
"version" : "2a2a2a2a2",
"index" : "2c2c2c2c2c2"
},
"Service3" : {
"code" : "Service4",
"version" : "3a3a3a3a3a",
"index" : "3c3c3c3c3c3"
}
}
}
'''
#convert above string to json
somejson = json.loads(myjson)
print(somejson["offers"]) # I tried so many variations to no avail.
Or, if you want the "code" stuffs :
>>> [s['code'] for s in somejson['offers'].values()]
['Service1', 'Service2', 'Service4']
somejson["offers"] is a dictionary. It seems you want to print its keys.
In Python 2:
print(somejson["offers"].keys())
In Python 3:
print([x for x in somejson["offers"].keys()])
In Python 3 you must use the list comprehension because in Python 3 keys() is a 'view', not a list.
This should probably do the trick , if you are not certain about the number of Services in the json.
import json
myjson='''
{
"formatVersion" : "ABC",
"publicationDate" : "2017-10-06",
"offers" : {
"Service1" : {
"code" : "Service1",
"version" : "1a1a1a1a",
"index" : "1c1c1c1c1c1c1"
},
"Service2" : {
"code" : "Service2",
"version" : "2a2a2a2a2",
"index" : "2c2c2c2c2c2"
},
"Service3" : {
"code" : "Service4",
"version" : "3a3a3a3a3a",
"index" : "3c3c3c3c3c3"
}
}
}
'''
#convert above string to json
somejson = json.loads(myjson)
#Without knowing the Services:
offers = somejson["offers"]
keys = offers.keys()
for service in keys:
print(somejson["offers"][service]["code"])
Can you please let me know if I have a rest service URL like
http://domain.ca/ArcGIS/rest/services/appData?f=json&pretty=true
which looks like
{"currentVersion" : 10.05,
"folders" : [],
"services" : [
{"name" : "appData/Drainage", "type" : "MapServer"},
{"name" : "appData/Parks", "type" : "MapServer"},
{"name" : "appData/Planning", "type" : "MapServer"},
{"name" : "appData/QNet", "type" : "MapServer"},
{"name" : "appData/Sanitary", "type" : "MapServer"},
{"name" : "appData/Street_Lights", "type" : "MapServer"},
{"name" : "appData/Survey", "type" : "MapServer"},
{"name" : "appData/Transportation", "type" : "MapServer"},
{"name" : "appData/Water", "type" : "MapServer"}
]
}
How can load all names after appData/ to a list called servicesList in python?
I tried something like
myUrl = "http://domain.ca/ArcGIS/rest/services"
myRequest = myUrl
response = urllib2.urlopen(myRequest)
myJSON = response.read()
but not sure this correct way?!
serviceList= []
for x in myJSON["services"]:
name = x["name"]
serviceList.append(name[name.index("/")+1:]) #Find the index of the / and add everything after it to the list
This would loop over all the names in the services and add the part after the / to the service list as you want.
EDIT:
You will also have to convert the string you read to JSON first. To do that:
import json
newJSON = json.loads(myJSON)
You can find documentation about json here
I'm trying to contact SOAP api with xml defined as: http://www.etrzby.cz/assets/cs/prilohy/EETXMLSchema.xsd . I've used this question ( How to construct SOAP message with pysimplesoap? ) and created following code in python :
import zeep
import datetime
wsdl = 'http://www.etrzby.cz/assets/cs/prilohy/EETServiceSOAP.wsdl'
client = zeep.Client(wsdl=wsdl,transport=transport)
daco = client.service.OdeslaniTrzby(Hlavicka = {
'uuid_zpravy' : '1',
'dat_odesl' : datetime.datetime.now(),
'prvni_zaslani' : '1',
'overeni' : "true"
}, Data={
'dic_popl' : '',
#'dic_poverujiciho' : '',
'id_provoz' : '151151',
'id_pokl' : '102',
'porad_cis' : '1',
'dat_trzby' : datetime.datetime.now(),
'celk_trzba' : '100',
'rezim' : '0'
}, KontrolniKody = {
'pkp' : {'digest': 'SHA256', 'cipher' : 'RSA2048', 'encoding' : 'base64'},
'bkp' : {'digest': 'SHA1', 'encoding' : 'base16'}
})
My question is following, the part with "KontrolniKody" at the end contains pkp and bkp elements. Pkp should have attributes digest, cipher and encoding (not sure if I put that correctly inside) and it should also contain the ~340 chars of generated code but I'm not sure where or how to put that in the element.
Anyone got any ideas? Thanks for the help either way.
I want to get weather data in spotfire as a html data table. Spotfire does provide Ironpython support but not the flexibility to add our own modules. So being a shorthand here. Using iframe and src as api doesnt help in this case.
My Script:
import clr
clr.AddReference('System.Data')
clr.AddReference('System.Web.Extensions')
import System
from System import DateTime
from System.Data import DataSet, DataTable
from System.IO import StreamReader, StreamWriter, MemoryStream, SeekOrigin
from System.Net import HttpWebRequest
from System.Web.Script.Serialization import JavaScriptSerializer
from Spotfire.Dxp.Data import DataType, DataTableSaveSettings
from Spotfire.Dxp.Data.Import import TextFileDataSource, TextDataReaderSettings
#uri = "http://api.openweathermap.org/data/2.5/weather?q=London&appid=ec0313a918fa729d4372555ada5fb1f8"
uri = "http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=ec0313a918fa729d4372555ada5fb1f8"
webRequest = HttpWebRequest.Create(uri)
response = webRequest.GetResponse()
streamReader = StreamReader(response.GetResponseStream())
jsonData = streamReader.ReadToEnd()
js = JavaScriptSerializer()
dataDict = js.Deserialize(jsonData, object)
print dataDict
# Close the connection
response.Close()
I need to extract some common values for multiple cities like: Name, Id, Description, temperature from the dictionary dataDict.
I am hitting a stone here.
It would be great if you can help me/ guide me on how to get these values from this complex dictionary.
Example dataDict: Dictionary[str, object]({'cnt' : 3, 'list' : Array[object]((Dictionary[str, object]({'coord' : Dictionary[str, object]({'lon' : <System.Decimal object at 0x0000000000000055 [37.62]>, 'lat' : <System.Decimal object at 0x0000000000000056 [55.75]>}), 'sys' : Dictionary[str, object]({'type' : 1, 'id' : 7323, 'message' : <System.Decimal object at 0x0000000000000057 [0.2107]>, 'country' : 'RU', 'sunrise' : 1484372967, 'sunset' : 1484400490}), 'weather' : Array[object]((Dictionary[str, object]({'id' : 802, 'main' : 'Clouds', 'description' : 'scattered clouds', 'icon' : '03d'}))), 'main' : Dictionary[str, object]({'temp' : <System.Decimal object at 0x0000000000000058 [-1.5]>, 'pressure' : 1009, 'humidity' : 80, 'temp_min' : -2, 'temp_max' : -1}), 'visibility' : 10000, 'wind' : Dictionary[str, object]({'speed' : 6, 'deg' : 160, 'gust' : 12}), 'clouds' : Dictionary[str, object]({'all' : 40}), 'dt' : 1484398800, 'id' : 524901, 'name' : 'Moscow'}), Dictionary[str, object]({'coord' : Dictionary[str, object]({'lon' : <System.Decimal object at 0x0000000000000059 [30.52]>, 'lat' : <System.Decimal object at 0x000000000000005A [50.43]>}), 'sys' : Dictionary[str, object]({'type' : 1, 'id' : 7358, 'message' : <System.Decimal object at 0x000000000000005B [0.1886]>, 'country' : 'UA', 'sunrise' : 1484373141, 'sunset' : 1484403724}), 'weather' : Array[object]((Dictionary[str, object]({'id' : 804, 'main' : 'Clouds', 'description' : 'overcast clouds', 'icon' : '04d'}))), 'main' : Dictionary[str, object]({'temp' : 3, 'pressure' : 998, 'humidity' : 86, 'temp_min' : 3, 'temp_max' : 3}), 'visibility' : 10000, 'wind' : Dictionary[str, object]({'speed' : 4, 'deg' : 170, 'var_beg' : 100, 'var_end' : 210}), 'clouds' : Dictionary[str, object]({'all' : 90}), 'dt' : 1484398800, 'id' : 703448, 'name' : 'Kiev'}), Dictionary[str, object]({'coord' : Dictionary[str, object]({'lon' : <System.Decimal object at 0x000000000000005C [-0.13]>, 'lat' : <System.Decimal object at 0x000000000000005D [51.51]>}), 'sys' : Dictionary[str, object]({'type' : 1, 'id' : 5091, 'message' : <System.Decimal object at 0x000000000000005E [0.1699]>, 'country' : 'GB', 'sunrise' : 1484380764, 'sunset' : 1484410813}), 'weather' : Array[object]((Dictionary[str, object]({'id' : 501, 'main' : 'Rain', 'description' : 'moderate rain', 'icon' : '10d'}))), 'main' : Dictionary[str, object]({'temp' : <System.Decimal object at 0x000000000000005F [4.01]>, 'pressure' : 1020, 'humidity' : 80, 'temp_min' : 2, 'temp_max' : 6}), 'visibility' : 10000, 'wind' : Dictionary[str, object]({'speed' : <System.Decimal object at 0x0000000000000060 [5.7]>, 'deg' : 290}), 'clouds' : Dictionary[str, object]({'all' : 20}), 'dt' : 1484400000, 'id' : 2643743, 'name' : 'London'})))})
I'm trying out json since I have to work with Cisco API and I can't figure out how to loop through the json object.I can get my keys but i can't get the values.
I am using http://www.jsoneditoronline.org/ to me understand json format but this is what I have so far..
json file :
{
"queryResponse" : {
"#rootUrl" : "\/webacs\/data",
"#requestUrl" : "https : \/\/192.168.116.207\/webacs\/api\/v1\/data\/DeviceGroups\/42",
"#responseType" : "getEntity",
"entity" : {
"#url" : "\/webacs\/data\/className\/15",
"#type" : "className",
"#dtoType" : "deviceGroupsDTO_$$_javassist_5196",
"deviceGroupsDTO" : {
"#id" : "15",
"#displayName" : "String value",
"clearedAlarms" : 1,
"criticalAlarms" : 1,
"groupId" : 2,
"groupName" : "String value",
"informationAlarms" : 1,
"majorAlarms" : 1,
"minorAlarms" : 1,
"name" : "String value",
"warningAlarms" : 1
}
}
}
}
My python script :
import json
jsondata = json.load(open('data.json'))
for rows in jsondata['queryResponse']['entity']['deviceGroupsDTO']:
print(rows)
it print's :
name
#id
warningAlarms
#displayName
informationAlarms
clearedAlarms
majorAlarms
groupId
groupName
criticalAlarms
minorAlarms
not sure what i'm doing wrong...
jsondata['queryResponse']['entity']['deviceGroupsDTO'] is a dictionary.
Iterate over items() to get key, value pairs:
for key, value in jsondata['queryResponse']['entity']['deviceGroupsDTO'].items():
print(key, value)
Note that, in case of python2, you would better use iteritems() in place of items().
See also: What is the difference between dict.items() and dict.iteritems()?