I am parsing a JSON file with Python. One of they keys I am trying to parse has a float value, and I am getting the following error: TypeError: list indices must be integers, not str. Below is the code, JSON, and full traceback.
Code:
import json
with open('output.json') as f:
data = json.load(f)
for host in data['ASSET_DATA_REPORT']['HOST_LIST']['HOST']:
print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])
JSON:
{
"ASSET_DATA_REPORT":{
"HOST_LIST":{
"HOST":[
{
"IP":{
"network_id":"0"
},
"TRACKING_METHOD":"EC2",
"ASSET_TAGS":{
"ASSET_TAG":[
"EC2 Running",
"IF - Database - MySQL"
]
},
"DNS":"i-xxxxxxx",
"EC2_INSTANCE_ID":"i-xxxxxx",
"EC2_INFO":{
"PUBLIC_DNS_NAME":"ec2-xxxxxxxx.amazonaws.com",
"IMAGE_ID":"ami-xxxxxx",
"VPC_ID":"vpc-xxxxxx",
"INSTANCE_STATE":"RUNNING",
"PRIVATE_DNS_NAME":"ip-xxxx.ec2.internal",
"INSTANCE_TYPE":"m3.xlarge"
},
"VULN_INFO_LIST":{
"VULN_INFO":[
{
"CVSS_FINAL":"3.6"
}
]
}
}
]
}
}
}
Traceback:
Traceback (most recent call last):
File "json_format.py", line 11, in <module>
print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])
TypeError: list indices must be integers, not str
The dictionary containing the "CVSS_FINAL" key is actually itself in a list. Try:
print(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])
As an aside, if you want to store this value as type float in Python (rather than string), you could do:
value = float(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])
Related
This is my output.json file:
{
"ParsedResults": [
{
"TextOverlay": {
"Lines": [],
"HasOverlay": false,
"Message": "Text overlay is not provided as it is not requested"
},
"TextOrientation": "0",
"FileParseExitCode": 1,
"ParsedText": "180 Grade IV\r\n\u0103\u021ar: Class VIII Pass\r\nwww.facebook.com, Since 2012\r\n",
"ErrorMessage": "",
"ErrorDetails": ""
}
],
"OCRExitCode": 1,
"IsErroredOnProcessing": false,
"ProcessingTimeInMilliseconds": "343",
"SearchablePDFURL": "Searchable PDF not generated as it was not requested."
}
I am trying to get the ParsedText value from this JSON file.
This is my the code I am using:
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults']['TextOverlay']['ParsedText'])
f.close()
Facing this error:
TypeError: list indices must be integers or slices, not str
How to read that particular value from ParsedText, please guide. Thanks in Advance
ParsedResults is not an object, it's a list
try this:
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['ParsedText'])
f.close()
data['ParsedResults'] is a list, you need to use the index to parse, So you are getting TypeError: list indices must be integers or slices, not str
use data['ParsedResults'][0].
use the following,
import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['TextOverlay']['ParsedText'])
f.close()
What I want to do is remove the array containing "Nike" under the "Shoe" variable.
Here is the Json file:
{
"Shoes/Colorways":
[
{
"Shoe": "Nike",
"Colorway": "Blue"
},
{
"Shoe": "Jordan",
"Colorway": "Blue"
}
]
}
I want the end result of the Json file to look like this:
{
"Shoes/Colorways":
[
{
"Shoe": "Jordan",
"Colorway": "Blue"
}
]
}
Here is the code I used to try to remove the array with "Nike":
import json
path = 'keywords.json'
with open(path, 'r') as f:
data = json.load(f)
for info in data['Shoes/Colorways']:
if info['Shoe'] == 'Nike':
data.remove(info['Shoe'])
data.remove(info['Colorway'])
else:
pass
print(data)
Here is the error:
Traceback (most recent call last):
File "c:\Users\TestUser\Desktop\Projects\Programs\json.py", line 10, in <module>
data.remove(info['Shoe'])
AttributeError: 'dict' object has no attribute 'remove'
I realized that .remove is only for lists and I cannot seem to find out how to do what I need to do in this scenario.
Try this:
import json
path = 'keywords.json'
with open(path, 'r') as f:
data = json.load(f)
data['Shoes/Colorways'] = [info for info in data['Shoes/Colorways'] if info['Shoe'] != 'Nike']
print(data)
The error is telling you, .remove does not exist on a dict object. Notice carefully that data is a dict. You should be calling .remove on the list - data['Shoes/Colorways'] is the list you need to remove from.
It would, however, be far better to simply use a list comprehension that filters out the element instead
data['Shoes/ColorWays'] = [x for x in data['Shoes/ColorWays'] if x['Shoe'] != 'Nike']
Remove operation doesn't exist in the dictionary. Better to skip some value that is not necessary.
print([info for info in data['Shoes/Colorways'] if info['Shoe'] != 'Nike'])
I'm trying to loop through this json string
"layoutOptions": {
"titleText": "Route Number",
"authorText": "West LA Yard",
"copyrightText": "",
"customTextElements": [{
"Date": "9/11/2018, 7:37:35 AM"
}
],
"scaleBarOptions": {
"metricUnit": "esriKilometers",
"metricLabel": "km",
"nonMetricUnit": "esriMiles",
"nonMetricLabel": "mi"
},
"legendOptions": {
"operationalLayers": [{
"id": "ParcelRouteEditingTest_1458"
}, {
"id": "ParcelRouteEditingTest_1259"
}
]
}
}
I keep running to this error list indices must be integers, not str
layoutOpsDict = layoutData["layoutOptions"]
dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict]
Error:
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
dateList = [dateEle["customTextElements"]["Date"] for dateEle in layoutOpsDict]
TypeError: string indices must be integers, not str
What is the best method to grab the date in customTextElements other than keep setting more variables to keep track of?
You are looping through every key instead of just "customTextElements" and not all of them have a list of dictionaries with "Date" as the key.
Since you only want to look through the values mapped to "customTextElements" you can only loop through that:
dateList = [dateEle["Date"] for dateEle in layoutOpsDict["customTextElements"]]
I have A json data like this:
json_data = '{"data":"[{"Date":"3/17/2017","Steam Total":60},{"Date":"3/18/2017","Steam Total":15},{"Date":"3/19/2017","Steam Total":1578},{"Date":"3/20/2017","Steam Total":1604}]", "data_details": "{"data_key":"Steam Total", "given_high":"1500", "given_low":"1000", "running_info": []}"}'
json_input_data = json_data["data"]
json_input_additional_info = json_data["data_details"]
I am getting an error:
TypeError: string indices must be integers, not str
I think there is an error in the json data. Can someone Help me on this?
In you code has some issues.
The code: json_input_data = json_data["data"], the variable json_data is not a Json Object, is a String Object and you try get a string position by string key, for get a Json object from string json use json api: json
You Json string isn't valid, this is a valid version:
{"data":[{"Date":"3/17/2017","Steam Total":60},{"Date":"3/18/2017","Steam Total":15},{"Date":"3/19/2017","Steam Total":1578},{"Date":"3/20/2017","Steam Total":1604}], "data_details": {"data_key":"Steam Total", "given_high":"1500", "given_low":"1000", "running_info": []}}
Now, your code works fine.
Try parsing your json_data to JSON format (with JSON.parse(json_data)). Currently it's type is string - which is exactly what your error says.
As Pongpira Upra pointed out, your json is not well formed and should be something like this.
{
"data":[
{
"Date":"3/17/2017",
"Steam Total":60
},
{
"Date":"3/18/2017",
"Steam Total":15
},
{
"Date":"3/19/2017",
"Steam Total":1578
},
{
"Date":"3/20/2017",
"Steam Total":1604
}
],
"data_details":{
"data_key":"Steam Total",
"given_high":"1500",
"given_low":"1000",
"running_info":[]
}
}
In order to retrieve information you should write
json_data[0]["Date"]
This would print "3/17/2017"
You declare a string called json_data and, well, then it acts like a string. That is what the exception tells you. Like others here tried to say - you do also have an error in your data, but the exception you supplied is due to accessing the string as if it was a dictionary. You need to add a missing call to e.g. json.loads(...).
You were right. Your JSON is indeed wrong.
Can you try using this json?
{
"data":[
{
"Date":"3/17/2017",
"Steam Total":60
},
{
"Date":"3/18/2017",
"Steam Total":15
},
{
"Date":"3/19/2017",
"Steam Total":1578
},
{
"Date":"3/20/2017",
"Steam Total":1604
}
],
"data_details":{
"data_key":"Steam Total",
"given_high":"1500",
"given_low":"1000",
"running_info":[]
}
}
I have to following bit of JSON data which is a snippet from a large file of JSON.
I'm basically just looking to expand this data.
I'll worry about adding it to the existing JSON file later.
The JSON data snippet is:
"Roles": [
{
"Role": "STACiWS_B",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTTstSTBWS-0001",
"TemplateName": "W2K16_BETA_4CPU",
"Hypervisor": "sys2Director-pool4",
"InCloud": false
}
}
],
So what I want to do is to make many more datasets of "role" (for lack of a better term)
So something like this:
"Roles": [
{
"Role": "Clients",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTClients-0001",
"TemplateName": "Win10_RTM_64_EN_1511",
"Hypervisor": "sys2director-pool3",
"InCloud": false
}
},
{
"Role": "Clients",
"Settings": {
"HostType": "AsfManaged",
"Hostname": "JTClients-0002",
"TemplateName": "Win10_RTM_64_EN_1511",
"Hypervisor": "sys2director-pool3",
"InCloud": false
}
},
I started with some python code that looks like so, but, it seems I'm fairly far off the mark
import json
import pprint
Roles = ["STACiTS","STACiWS","STACiWS_B"]
RoleData = dict()
RoleData['Role'] = dict()
RoleData['Role']['Setttings'] = dict()
ASFHostType = "AsfManaged"
ASFBaseHostname = ["JTSTACiTS","JTSTACiWS","JTSTACiWS_"]
HypTemplateName = "W2K12R2_4CPU"
HypPoolName = "sys2director"
def CreateASF_Roles(Roles):
for SingleRole in Roles:
print SingleRole #debug purposes
if SingleRole == 'STACiTS':
print ("We found STACiTS!!!") #debug purposes
NumOfHosts = 1
for NumOfHosts in range(20): #Hardcoded for STACiTS - Generate 20 STACiTS datasets
RoleData['Role']=SingleRole
RoleData['Role']['Settings']['HostType']=ASFHostType
ASFHostname = ASFBaseHostname + '-' + NumOfHosts.zfill(4)
RoleData['Role']['Settings']['Hostname']=ASFHostname
RoleData['Role']['Settings']['TemplateName']=HypTemplateName
RoleData['Role']['Settings']['Hypervisor']=HypPoolName
RoleData['Role']['Settings']['InCloud']="false"
CreateASF_Roles(Roles)
pprint.pprint(RoleData)
I keep getting this error, which is confusing, because I thought dictionaries could have named indices.
Traceback (most recent call last):
File ".\CreateASFRoles.py", line 34, in <module>
CreateASF_Roles(Roles)
File ".\CreateASFRoles.py", line 26, in CreateASF_Roles
RoleData['Role']['Settings']['HostType']=ASFHostType
TypeError: string indices must be integers, not str
Any thoughts are appreciated. thanks.
Right here:
RoleData['Role']=SingleRole
You set RoleData to be the string 'STACiTS'. So then the next command evaluates to:
'STACiTS'['Settings']['HostType']=ASFHostType
Which of course is trying to index into a string with another string, which is your error. Dictionaries can have named indices, but you overwrote the dictionary you created with a string.
You likely intended to create RoleData["Settings"] as a dictionary then assign to that, rather than RoleData["Role"]["Settings"]
Also on another note, you have another syntax error up here:
RoleData['Role']['Setttings'] = dict()
With a mispelling of "settings" that will probably cause similar problems for you later on unless fixed.