I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.
Traceback (most recent call last):
File "Translator.py", line 42, in <module>
main()
File "Translator.py", line 38, in main
parse_json(trans_text)
File "Translator.py", line 27, in parse_json
result = json['translations']['translatedText']
TypeError: list indices must be integers, not str
This is my JSON object looks like,
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
and this is my python piece of code for it.
def parse_json(trans_text):
json = simplejson.loads(str(trans_text).replace("'", '"'))
result = json['translations']['translatedText']
print result
any idea on it?
json['translations'] is a list by your definition, so its indices must be integers
to get a list of translations:
translations = [x['translatedText'] for x in json['translations']]
another way:
translations = map(lambda x: x['translatedText'], json['translations'])
json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:
from operator import itemgetter
print map(itemgetter('translatedText'), json['translations'])
See the implementation of detect_language_v2() for another usage example.
Related
I'm writing a program to sort through csv files. It is supposed to pull lines from the files and based on whether a "donor" is already in the dictionary, either add the "donor" to the dictionary or append the information in the line to the old value. I'm getting the error statement:
error statement: File "C:/Users/riley/Desktop/Python Files/MYLATEST1.py", line 27, in
donors[donor] = [[data]]
builtins.TypeError: list indices must be integers or slices, not tuple
I'm new to python, but it seems as if python is interpreting my dictionary as a list. Is that what's going on? If so, why? Thanks for any help!
def createDonorDirect():
listoffiles = glob.glob('C:/Users/riley/Desktop/mydata//*.csv') #glob allows you to create a list of files/folders that match wildcard expression in this case all the csv files in the directory
# Create donors directory
donors = {}
for filename in listoffiles:
with open(filename) as file:
for line in file:
# line processing stuff
data = line.split(',')
donor = ''.join(data[3,5,7])
# populate data structure
if donor in donors:
donors[donor].append(data)
else:
donors[donor] = [[data]]
The reason for the error is you are assigning donor to tuple value as key, which is wrong here since tuple content multiple values.
sample problem regeneration with code:-
>>> data=['HI','Hello','How','are','you','my','name','is']
>>> donor = ''.join(data[3,5,7])
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
donor = ''.join(data[3,5,7])
**TypeError: list indices must be integers or slices, not tuple**
>>>
second simplified code:-
>>> data[3,5,7]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
data[3,5,7]
TypeError: list indices must be integers or slices, not tuple
Tuple declaration can be little confusing sometimes.
For example: SOME_CONSTANT = 1, is same as SOME_CONSTANT = (1, ) . Both are a tuple.
On the other hand, SOME_CONSTANT = (1) will be same as SOME_CONSTANT = 1. Both are an integer.
In your case you just need to change:
donor = ''.join(data[3,5,7])
to
donor = ''.join(data[3] + data[5] + data[7])
Example:
data=['A','B','C','D','E','F','G','H']
print ''.join(data[3] + data[5] + data[7])
DFH
How do you iterate a array of javax.management.openmbean.CompositeDataSupport?
myBean = ObjectName('com.oracle.sdp.messaging:Location=my_soa_server,name=EmailDriverConfig,type=SDPMessagingDriverConfig,Application=usermessagingdriver-email')
driverParams = mbs.getAttribute(myBean,'DriverParameterProperties')
for param in driverParams:
####How to do iterate and do an if on a name#####
print param.getName()
If I do something like this I am getting..
Traceback (innermost last):
File "<console>", line 1, in ?
AttributeError: getName
I have verified that when you execute driverParams[0] that I am getting something like this
javax.management.openmbean.CompositeDataSupport(compositeType=javax.management.openmbean.CompositeType(name=Property,items=((itemName=allowedValues,itemType=javax.management.openmbean.ArrayType(name=[Ljavax.management.openmbean.CompositeData;,dimension=1,elementType=javax.management.openmbean.CompositeType(name=AllowedValue,items=((itemName=label,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=value,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)))),primitiveArray=false)),(itemName=description,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=encodedCredential,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=mandatory,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=name,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=type,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=value,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)))),contents={allowedValues=[], description=Supported Delivery Types, encodedCredential=false, mandatory=yes, name=SupportedDeliveryTypes, type=java.lang.String, value=EMAIL})
Looking at the attribute, I would like to validate the SupportedDeliveryTypes value
name=SupportedDeliveryTypes
value=EMAIL
description=Supported Delivery Types
CompositeDataSupport is not an array.
To view its content you can try using toString() (in your sample driverParams[0].toString()) or access values with values() or get(String key) / getAll(String[] keys).
For example, try with:
myBean = ObjectName('com.oracle.sdp.messaging:Location=my_soa_server,name=EmailDriverConfig,type=SDPMessagingDriverConfig,Application=usermessagingdriver-email')
driverParams = mbs.getAttribute(myBean,'DriverParameterProperties')
for param in driverParams:
print param.toString()
I am having some trouble with the following JSON and reading the data, having looked though some of the other questions nothing seems to come up with a solution unless I am missing something..
Help always appreciated :)
JSON:
{"ships":{"2":{"name":"Asp","alive":true,"id":2},"3":{"starsystem":{"systemaddress":"670417429889","id":"670417429889","name":"Diaguandri"},"station":{"id":3223343616,"name":"Ray Gateway"},"name":"SideWinder","alive":true,"id":3},"12":{"starsystem":{"systemaddress":"18263140541865","id":"73228","name":"Barnard's Star"},"station":{"id":128147960,"name":"Miller Depot"},"name":"Viper_MkIV","alive":true,"id":12},"13":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"Type7","alive":true,"id":13},"14":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"SideWinder","alive":true,"id":14}}}
Python Code:
import json
with open('profile.txt') as edstats:
data = json.load(edstats)
def shipYard():
ships = [item["name"] for item in data['ships']]
print json.dumps(ships,indent=4)
Error:
>>> shipYard()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "arg_test_ship.py", line 7, in shipYard
ships = [item["name"] for item in data['ships']]
TypeError: string indices must be integers
The issue you're missing is that data['ships'] is itself another dictionary object. When you iterate through a dictionary as you have in shipYard(), you will just get the keys:
>>> a={'a':1,'b':2}
... [i for i in a]
7: ['a','b']
You want to access the name attribute WITHIN the dictionary, for which you would use the dictionary.items() method:
>>> data = '''{"ships":{"2":{"name":"Asp","alive":true,"id":2},"3":{"starsystem":{"systemaddress":"670417429889","id":"670417429889","name":"Diaguandri"},"station":{"id":3223343616,"name":"Ray Gateway"},"name":"SideWinder","alive":true,"id":3},"12":{"starsystem":{"systemaddress":"18263140541865","id":"73228","name":"Barnard's Star"},"station":{"id":128147960,"name":"Miller Depot"},"name":"Viper_MkIV","alive":true,"id":12},"13":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"Type7","alive":true,"id":13},"14":{"starsystem":{"systemaddress":"673101653409","id":"673101653409","name":"Brestla"},"station":{"id":3224813312,"name":"Roed Odegaard Port"},"name":"SideWinder","alive":true,"id":14}}}'''
... import json
... data = json.loads(data)
>>> ships = [item['name'] for index, item in data['ships'].items()]
>>> ships
8: [u'Viper_MkIV', u'SideWinder', u'Asp', u'Type7', u'SideWinder']
>>>
Or, if you don't need the indexes, use the dictionary values() method:
>>> ships = [item['name'] for item in data['ships'].values()]
>>> ships
9: [u'Viper_MkIV', u'SideWinder', u'Asp', u'Type7', u'SideWinder']
>>>
I want to split the History_Data with , and put into an dictionary , then put the dictionary to a one dimension array then access them . But it seems have some error . How can I solve that?
here is my code
History_Data = ("2004/01/20,000006,29,28,13,33,34,32,43",
"2004/01/18,000005,36,22,44,34,46,29,37",
"2004/01/16,000004,02,13,34,44,06,40,14",
"2004/01/14,000003,29,28,13,33,34,32,43",
"2004/01/12,000002,32,15,14,29,39,20,43",
"2004/01/10,000001,30,29,18,34,19,28,12")
Dataset = ()
for Line in History_Data:
Item = {}
Parts = Line.split(",")
Item['date'] = Parts[0]
Item['serial'] = Parts[1]
Item['numbers'] = Parts[2:len(Parts)]
Dataset.append(Item)
for Element in Dataset:
print(Element)
Error message
Traceback (most recent call last):
File ".\1.py", line 18, in <module>
Dataset.append(Item)
AttributeError: 'tuple' object has no attribute 'append'
tuple is an immutable type in Python so gets no method append. For your need, use a list, Dataset = [], not a tuple, Dataset = ().
Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained). Thanks!! -OSFTW
It looks like you want to interpret the strings as integers. Use int to do this:
chkseq = [int(line) for line in open("sequence.txt")]
It can also be written using map instead of a list comprehension:
chkseq = map(int, open("sequence.txt"))
iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.
Say your array is called input, and you want to store the value in an array called chkseq, your code would be:
chkseq = [int(i) for i in input]
Or, if you wanted to do everything all in one line:
chkseq = [int(i.strip()) for i in open("sequence.txt")]
Passing a string to the int constructor will attempt to turn it into a int.
>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'