How do I add a Key/Value in JSON with Python? [duplicate] - python

This question already has answers here:
How to update json file with python [duplicate]
(4 answers)
Closed 5 years ago.
This may sound like an average question, but I haven't found a good answer to what I am trying to do.
Take d.json:
{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}}
I'm trying to add this to it, separated by commas:
{'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}
I tried multiple ways to do it, but none works. Here's my current code
a = d[toolname] = {str(toolname):{"Info":{"Description": tooldesc, "Download Link": toollink}}}
f.write(str(a))
f.close()
return jsonify(a), 201
My whole goal is to write
{'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}
to d.json like this
{"SDA":{"Info":{"Description":"Anti Advertisment Bot, Blocks invites extensively.","Download Link":"http://sda.khionu.net/docs/, http://sda.khionu.net/docs/"}}, "Unit 02":{"Info":{"Description":"Server logging bot, c!serverlogs 'server name here if spaces' <# 1-9999>","Download Link":"https://discordapp.com/oauth2/authorize?client_id=222881716606468096&scope=bot&permissions=32768"}}, {'Ctest': {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}}

Use json module for that, code below shall give you the clue:
import json
data = json.load('path_to_json_file')
data['key'] = 'value'
json.dump('path_to_json_file', data)

You can use this:
jsonObject['Ctest'] = {'Info': {'Description': 'Hi', 'Download Link': 'Sure'}}

Thanks to franklinsijo, I found an answer, and it is a duplicate, surprise surprise.
I reformatted the code to this:
a = d[toolname] = {toolname:{"Info":{"Description": tooldesc, "Download Link": toollink}}}
with open('data1.json', 'w') as f:
f.write(json.dumps(d))
f.close()
return jsonify(a), 201
Thanks for answering guys, I'll flag as a duplicate of his question.

Related

Retrieving values from dicts

Sorry brand new to python so this may be really simple.
I'm trying to retrieve a key value from a dictionary based on the users input. I'm currently trying an if/else statements but have also tried a for loop. My code is below, I just can't seem to find out why it isn't working.
import requests
import os
import json
orgUrl = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
payload = None
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Meraki-API-Key": os.environ.get('MERAKI_DASHBOARD_API_KEY')
}
orgResponse = requests.request('GET', orgUrl, headers=headers, data = payload)
orgResponseJson = orgResponse.json()
#print(orgResponseJson)
orgName = input("Please enter organisation name \n")
if orgName == (orgResponseJson.index['name']):
print (orgResponseJson.index['id'])
else:
print("Organisation does not exist")
If there's any study material out there someone could suggest that would be appreciated. The code is formatted correctly in the IDE but for some reason it hasn't copied across that way.
So I can't show the contents of the dictionary as it is business sensitive information but as an example the values are along the lines of {'name': business 1'}, 'id': 8384965'}}
So the code runs, it prints out the input, doesn't return the value 'id' and then continues to print out the else statement.
I guess it's moved onto the else statement because the if statement isn't looking in the dict?
************* UPDATE *****************
I've solved it. Whether it's best practice or not is another issue. I opted to use a for loop using the break command;
'''p
for orgLicense in orgResponseJson:
if orgName == (orgLicense['name']):
print(orgLicense['licensing'])
break
else:
orgName != (orgLicense['name'])
print("Organisation does not exist")
break
''''
Thank-you
Jake

How to access specific parts of JSON for API call - Python

I want to access 'employmentName' and 'jobTile' values.
But I keep on getting this error - KeyError: 'jobTitle' and KeyError: 'employmentName'
Here is my code below, please note I am not sharing the api URL on this question but it is present and working in the code.
api_three_url = "https://xxxx"
json_data_three = requests.get(api_three_url, headers=my_headers).json()
#print(json_data_three) #this prints the whole json data (working!)
print("So you have previously worked in", json_data_three['employmentName'],"as a", json_data_three['jobTitle'])
This is what the JSON looks like in python dict:
{
'hasAddedValue': False,
'employments': [{
'id': 527,
'employmentName': 'Sallys hair',
'jobTitle': 'Stylists',
'jobStartDate': '2019-03',
'jobEndDate': '2020-04',
'jobType': 'PAID',
'status': True,
'isJobCurrent': False
}]
}
Please guide me to where I am going wrong.
Many thanks :)
The employmentName and jobType fields are not at the top level in your JSON, hence Python is giving you KeyError. They are actually in one of the objects inside employments.
So if you want to obtain those fields from the first object inside employments, it would be:
json_data_three['employments'][0]['employmentName']

Python: Get Jira Tickets that returned an error

I'm using the atlassian rest API and creating issues through it. For accessing the API I'm using the JIRA-API-Wrapper see: https://pypi.org/project/jira/.
In my application I'm uploading a bunch of tickets. Due to performance reasons I'm using concurrent.futures. The tickets are uploaded via the following code:
fields = [{'project': 'Project', 'summary': 'New summary', 'issuetype': {'name': 'Task'}}, ....]
with concurrent.futures.ThreadPoolExecutor() as executor:
data = executor.map(jira.create_issue, fields)
My problem is, that I'm not really sure how to get the information, when a ticket couldn't be uploaded for some reason. Everytime a ticket couldn't be uploaded, the JIRA-Wrapper returns a JIRAError-Exception. Therefore, I somehow have to count whenever I get a JIRAError. But unfortunally I'm not sure how to count the errors.
I know that the result can be retrieved via:
for i in data:
counter = counter + 1
print(i)
But because data contains the JIRAErrors the above code fails. This is why I tried the following.
try:
for i in data:
print(i)
except:
print(fields[counter])
But when the exception appears the code just continues. Therefore I tried solutions with a while-loop, but they also didn't get the right solution.
Is there a way to get the tickets, which couldn't be uploaded?
I haven't used jira-python myself. I wrote my own python client that I've been using for years. I'll have to give this a try myself.
According to the documentation to create bulk issues:
https://jira.readthedocs.io/en/latest/examples.html#issues
issue_list = [
{
'project': {'id': 123},
'summary': 'First issue of many',
'description': 'Look into this one',
'issuetype': {'name': 'Bug'},
},
{
'project': {'key': 'FOO'},
'summary': 'Second issue',
'description': 'Another one',
'issuetype': {'name': 'Bug'},
},
{
'project': {'name': 'Bar'},
'summary': 'Last issue',
'description': 'Final issue of batch.',
'issuetype': {'name': 'Bug'},
}]
issues = jira.create_issues(field_list=issue_list)
Additionally, there is a note about the failures which you are interested in:
Using bulk create will not throw an exception for a failed issue
creation. It will return a list of dicts that each contain a possible
error signature if that issue had invalid fields. Successfully created
issues will contain the issue object as a value of the issue key.
So to see the ones that failed, you would iterate through issues and look for error signatures.
As far as performance issues, you could look at jira.create_issues(data, prefectch=false)
https://jira.readthedocs.io/en/latest/api.html#jira.JIRA.create_issues
prefetch (bool) – whether to reload the created issue Resource for
each created issue so that all of its data is present in the value
returned from this method.
However, if you must use concurrent.futures, note that it will likely fail when calling via jira.create_issue if jira object has a state that needs to be saved between calls to create_issue when being run async.
If a func call raises an exception, then that exception will be raised
when its value is retrieved from the iterator.
I would recommend using a separate jira object for each create_issue if you do not trust the create_issues() function.
def create_issue(fields):
print(fields)
j_obj = JIRA(...)
try:
ret = j_obj.create_issue(fields)
except:
# Do something here
ret = False
return ret
with concurrent.futures.ThreadPoolExecutor() as executor:
data = executor.map(create_issue, issue_list)
items = [item for item in data]
print(items)
# Interact with result
pdb.set_trace()
When you break into the trace, any successful issues created will be an Issue type, any failures will show up as False. This is just an example, and you can decide what you want to return, in whatever format you need.

how to get Parameters from a json file with python

I am working in Python with a JSON file. When I print date it comes out like this :
print (date['slot'])
[{'slot': 1, 'type': {'url': 'https://pokeapi.co/api/v2/type/11/', 'name':
'water'}}]
But I just want to get 'water'. I have been using different methods and it did not work. Can someone please help me to get just 'water' from the code?
print (date['slot'][0]['type']['name'])
OR
print (date['slot'][0]['type']['name'] if date['slot'] else None)
OR More generic
for sd in date['slot']:
print (sd['type']['name'])

how to define URL path in web develpoment

I am developing an app which has a hierarchy of course, chapter, and a lesson.
One course contains none of a chapter & one chapter contains multiple lessons. So I have defined the below mentioned URL so I just want your guys' suggestion if it needs some changes.
/courses
/courses/<:course_id>
/chapter/<:course_id>
/chapter/<:course_id>/<:chapter_id>
/lesson/<:course_id>/<:chapter_id>
/lesson/<:course_id>/<:chapter_id>/<:lesson_id>
If you want hierarchical URLs, I would use this:
/courses/
/courses/<:course_id>
/courses/<:course_id>/chapters/
/courses/<:course_id>/chapters/<:chapter_id>
/courses/<:course_id>/chapters/<:chapter_id>/lessons/
/courses/<:course_id>/chapters/<:chapter_id>/lessons/<:lesson_id>
Alternatively, you could go with something like this:
/courses
/courses/<:course_id>
/courses/<:course_id>/chapters/
/chapters/<:chapter_id>
/chapters/<:chapter_id>/lessons/
/lessons/<:lesson_id>
Depending on your requirements, you could just return the essential information about the nested resources and reference the full resource, e.g. like this:
GET /courses/123
{
'title': 'My course',
...
'chapters': [{
'url': '/chapters/456'
'title': 'Chapter 1'
}]
}

Categories