How to parse json in python - python

i want to get token through the result of REST API and it has done and success. the result of REST API shown below following print(result) of python
'{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}'
do you know how to get "Token" as variable?, so i can get to next step. thank you

You can use json.loads
import json
jObject = json.loads('{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}')
# This should give you the value you are looking for:
token = jObject["Token"]
print(token)

I have written a short write util function (below) which I include in every project I work on. So if your target file has a .json extension, it automatically format it into json.
eg. write(result, "dst_dir/dst_file.json")
import json
def write(content, file, **kwargs):
if not isinstance(file, str):
file = str(file)
if file.endswith('.json'):
with open(file, 'w') as f:
json.dump(content, f, indent=2, **kwargs)
else:
with open(file,'w') as f:
f.write(content, **kwargs)
write(result, "dst_dir/dst_file.json") # To run it with your result

Related

How would i delete something from a json file

I'm not sure how to delete something from a .json file
I've tryed looking it up and it still nothing :(
#bot.command()
async def afkremoveme(ctx):
#pls help me I'm lost!
no errors
I'm not sure what you want your command to do, but here's an example of how you would implement json into discord.py.
Here, whenever the command is executed, the bot opens a json file, reads the data, and sees if the message author is in the data. If the author is in the data, the key/value pair is deleted, and the data is rewritten into the json file:
import json
#bot.command()
async def afkremoveme(ctx):
f = "yourFile.json"
author = str(ctx.author.id)
with open(f, "r") as read_file:
data = json.load(read_file)
if author in data: # if any key in the dictionary is an integer, it is converted to a string when a json file is written
del data[author]
newData = json.dumps(data, indent=4)
with open(f, "w") as write_file:
write_file.write(newData)
await ctx.send(f"{ctx.author.display_name} is no longer afk...")
This is reading a json file that looks like this (replace 000000 with your id):
{
"000000" : "afk",
"someOtherGuy" : "afk"
}
All of this uses dictionaries and the json module. If you're unfamiliar with either of the concepts, here are a few links to help you out :-)
Python Dictionaries,
Python-Json

Converting dictionary as Json and append to a file

Scenario is i need to convert dictionary object as json and write to a file . New Dictionary objects would be sent on every write_to_file() method call and i have to append Json to the file .Following is the code
def write_to_file(self, dict=None):
f = open("/Users/xyz/Desktop/file.json", "w+")
if json.load(f)!= None:
data = json.load(f)
data.update(dict)
f = open("/Users/xyz/Desktop/file.json", "w+")
f.write(json.dumps(data))
else:
f = open("/Users/xyz/Desktop/file.json", "w+")
f.write(json.dumps(dict)
Getting this error "No JSON object could be decoded" and Json is not written to the file. Can anyone help ?
this looks overcomplex and highly buggy. Opening the file several times, in w+ mode, and reading it twice won't get you nowhere but will create an empty file that json won't be able to read.
I would test if the file exists, if so I'm reading it (else create an empty dict).
this default None argument makes no sense. You have to pass a dictionary or the update method won't work. Well, we can skip the update if the object is "falsy".
don't use dict as a variable name
in the end, overwrite the file with a new version of your data (w+ and r+ should be reserved to fixed size/binary files, not text/json/xml files)
Like this:
def write_to_file(self, new_data=None):
# define filename to avoid copy/paste
filename = "/Users/xyz/Desktop/file.json"
data = {} # in case the file doesn't exist yet
if os.path.exists(filename):
with open(filename) as f:
data = json.load(f)
# update data with new_data if non-None/empty
if new_data:
data.update(new_data)
# write the updated dictionary, create file if
# didn't exist
with open(filename,"w") as f:
json.dump(data,f)

Parsing tweets' text out of "Status" wrapper in json file

I used this tweepy-based code to pull the tweets of a given user by user_id. I then saved a list of all tweets of a given user (alltweets) to a json file as follows. Note that without "repr", i wasn't able to dump the alltweets list into json file. The code worked as expected
with open(os.path.join(output_file_path,'%s_tweets.json' % user_id), 'a') as f:
json.dump(repr(alltweets), f)
However, I have a side problem with retrieving the tweets after saving them to the json file. I need to access the text in each tweet, but I'm not sure how to deal with the "Status" wrapper that tweepy uses (See a sample of the json file attached).sample json file content
I tried to iterate over the lines in the file as follows, but the file is being seen as a single line.
with open(fname, 'r') as f:
for line in f:
tweet = json.loads(line)
I also tried to iterate over statuses after reading the json file as a string, as follows, but iteration rather takes place on the individual characters in the json file.
with open(fname, 'r') as f:
x = f.read()
for status in x:
"""code"""
Maybe not the prettiest solution but you could just declare Status as a dict and then eval the list (the whole content of the files).
Status = dict
f = open(fname, 'r')
data = eval(f.read())
f.close()
for status in data:
""" do your stuff"""

Modifying content of NamedTemporaryFile (Python 3)

I'm unable to modify the content of a NamedTemporaryFile after having created it initially.
As per my example below, I create a NamedTemporaryFile from the content of a URL (JSON data).
Then, what I aim to do is re-access that file, modify some of the content of the JSON in the file, and save it. The code below is my attempt to do so.
import json
import requests
from tempfile import NamedTemporaryFile
def create_temp_file_from_url(url):
response = requests.get(url)
temp_file = NamedTemporaryFile(mode='w+t', delete=False)
temp_file.write(response.text)
temp_file.close()
return temp_file.name
def add_content_to_json_file(json_filepath):
file = open(json_filepath)
content = json.loads(file.read())
# Add a custom_key : custom_value pair in each dict item
for repo in content:
if isinstance(repo, dict):
repo['custom_key'] = 'custom_value'
# Close file back ... if needed?
file.close()
# Write my changes to content back into the file
f = open(json_filepath, 'w') # Contents of the file disappears...?
json.dumps(content, f, indent=4) # Issue: Nothing is written to f
f.close()
if __name__ == '__main__':
sample_url = 'https://api.github.com/users/mralexgray/repos'
tempf = create_temp_file_from_url(sample_url)
# Add extra content to Temporary file
add_content_to_json_file(tempf)
try:
updated_file = json.loads(tempf)
except Exception as e:
raise e
Thanks for the help!
1: This line:
json.dumps(content, f, indent=4) # Issue: Nothing is written to f
doesn't dump content to f. It makes a string from content, with skipkeys value f, and then does nothing with it.
You probably wanted json.dump, with no s..
2: This line
updated_file = json.loads(tempf)
tries to load a JSON object from the temp filename, which isn't going to work. You'll have to either read the file in as a string and then use loads, or re-open the file and use json.load.

Read json file from python

I am trying to read a json file from python script using the json module. After some googling I found the following code:
with open(json_folder+json) as json_file:
json_data = json.loads(json_file)
print(json_data)
Where json_folder+json are the path and the name of the json file. I am getting the following error:
str object has no attribute loads.
The code is using json as a variable name. It will shadow the module reference you imported. Use different name for the variable.
Beside that, the code is passing file object, while json.loads accept a string.
Pass a file content:
json_data = json.loads(json_file.read())
or use json.load which accepts file-like object.
json_data = json.load(json_file)
import json
f = open( "fileToOpen.json" , "rb" )
jsonObject = json.load(f)
f.close()
it should seems you are doing in rather complicated way.
Try like this :-
json_data=open(json_file)
data = json.load(json_data)
json_data.close()
Considering the path to your json file is set to the variable json_file:
import json
with open(json_file, "rb") as f:
json_data = json.load(f)
print json_data
I Make This....
import urllib2
link_json = "\\link-were\\"
link_open = urllib2.urlopen(link_json) ## Open and Return page.
link_read = link_open.read() ## Read contains of page.
json = eval(link_read)[0] ## Transform the string of read in link_read and return the primary dictionary ex: [{dict} <- return this] <- remove this
print(json['helloKey'])
Hello World

Categories

Resources