Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Sorry I am a python beginner coming from a java background. I am doing something wrong and not finding it from google.
I have config_file.json:
{
key1: val1,
key2: val2,
keyArrayOfImportantVal : [ "str1", "str2", "str3"]
}
I am able to read in my json file and create a variable that maps to my json file
config_values = read_config_file('path to file')
#config_values has json as I expect
I need to iterate over the values in keyArrayOfImportantVal. I am just not finding what I need to do this.
I thought this should work, but it doesn't.
for val in config_values.keyArrayOfImportantVal:
print (val)
nor does
importantVals = _config_values.keyArrayOfImportantVal
for val in imporantVals:
prit(val)
you can read how properly read json file from here Reading and Writing JSON to a File in Python or you can use this snippet if it helps
import json
with open('path to file') as json_file:
data = json.load(json_file)
this will iterate all keys
for x in data:
print(x)
this will iterate in values in this key "keyArrayOfImportantVal"
for x in data['keyArrayOfImportantVal']:
print(x)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to python. I am trying to get value from a JSON File.
Here is my JSON file stored in static/tokens.json
{
"872387":"ABC",
"821483":"XYZ",
"575652":"KLM"
}
I want to read the get the value of Key(821483). which is XYZ.
Here is what I am doing
I am reading Json file
token = json.load(open(os.path.join(app.root_path, "static", "tokens.json")))
print(token['821483'])
But it gives me this error:
print(token['821483']) TypeError: string indices must be integers
I have also tried this
with open(os.path.join(app.root_path, "static", "tokens.json")) as read_file:
data = json.load(read_file)[1]
print("Type of deserialized data: ", type(data))
print(data['821483'])
But Again I am getting the same error.
I have seen similar questions on Stackoverflow. And what I have understood so far is that
tokens = json.load(open(os.path.join(app.root_path, "static", "tokens.json"))) converts Json to a List. How can I solve this problem? I don't want to change the structure of JSON file.
How can I convert this JSON file into a dictionary not into a list so that I can access the values using a key?
When you use json.load() python automatically converts to dict, see here so you don't need to convert to dict again
import json
data = json.load(open("static/tokens.json"))
Now check what is in data and the type of data:
{'872387': 'ABC', '821483': 'XYZ', '575652': 'KLM'} <class 'dict'>
We sucessfully convert it to dict so now you can iterate:
for key, value in data.items():
if key == "821483":
print({key: value})
Out: {'821483': 'XYZ'}
If you don't want to iterate you can simply use dict_object.get(value)
print(data.get("821483"))
Out: XYZ
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
{
"appconfig": {
"username" : "test",
"password" : "testpassowrd"
},
"bot": [
{
"contains": [],
"exact": ["hi","hy","hey","hlw"],
"response": "hey there"
},
{
"contains": [],
"exact": ["gm","good morning","vgm"],
"response": "good morning"
}
],
"blocked": [],
}
i am storing json snippet in son file and opening file during execution :
with open('/data.json', 'r') as f:
data = json.load(f)
i am looking forward to matching string with an exact array in JSON one by one in python. what is the best way possible using a lambda filter?
For example
user_msg = 'hi'
i have to match one by one in each exact array if a value exists send the response.
Thanks in advance.
EDIT : 1
#Tom Robinson pointed out the solution which seems to be working well. But I would suggest to account for the complexity and the size of JSON as well. If the size is huge we need to look for solutions that load JSON as a stream, not as a file like https://github.com/henu/bigjson
Secondly, while comparing in is a simpler operation and easiest to point, but it is known to having taxing performance impact. Based on the size of the list, you may want to convert that into a set and try to find the value.
Lastly, the program seems to be working for dataset, however we need to account for missing keys, I would like to change the above to use dict.get() in place of dict['key'], So the finally extending the solution given by TOM may look like:
def getResponse(user_msg):
with open('/data.json', 'r') as f:
data = json.load(f)
for data_set in data.get("bot",{}):
_extract = data_set.get("exact",None)
if _extract and user_msg in _extract :
return data_set.get("response",None)
getResponse(user_msg)
Using this we can avoid doing key checks.
Through iterating over every possible data set, you can run checks every time like this:
def getResponse(user_msg):
for data_set in data["bot"]:
if user_msg in data_set["exact"]:
return data_set["response"]
getResponse(user_msg)
This assumes that data is already defined and in the global scope, whereas the next function reads the file internally:
def getResponse(user_msg):
with open('/data.json', 'r') as f:
data = json.load(f)
for data_set in data["bot"]:
if user_msg in data_set["exact"]:
return data_set["response"]
getResponse(user_msg)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've looked through the documentation here: https://developers.google.com/youtube/v3/docs/videos
But am unsure how to access status.rejectionReason with python. I've been using youtube-uploader for my uploading, and I dont believe there is any commands to return the reason a video was rejected. The ideal scenario would be to get a list of all my videos, check which ones have been rejected, then return the links of the ones that have been rejected.
From what I can see the rejectionReason is within a JSON "videos resource" format. You can access this with Python's built-in JSON library:
from json import load
with open('video.json') as file: # Opens the JSON file and assigns it to the variable 'file' within the loop
data = load(f) # Loads the file into a dictionary which you can access with key:value pairs
The JSON file provided as a sample on the site follows this format for the rejectionReason:
"status": {
"uploadStatus": string,
"failureReason": string,
"rejectionReason": string,
"privacyStatus": string,
"publishAt": datetime,
"license": string,
"embeddable": boolean,
"publicStatsViewable": boolean
}
So your final script would look like this I believe:
from json import *
def get_rejection_reason(file):
with open(file) as f:
data = load(f)
return data["status"]["rejectionReason"]
get_rejection_reason("video.json")
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How do I make a REST query in python with a comparison statement? Like (in quasi code):
result = foo where bar > 10
I want to make a rest api query from python 2.7 using requests. What I want is to get all articles that have been updated during the last 24 hours.
In javascript it looks like this and it works great:
http://myDatabase.domain.io/api/v1/article/q={"update_date":{"$gt":"2018-08-27 13:44"}}
I just can't recreate this with python. Does anyone know how?
Assuming
that's actually ?q=, i.e. a query string
and the query should be JSON (it looks like it)
and the endpoint returns JSON:
import requests, json
query = json.dumps(
{"update_date": {"$gt": "2018-08-27 13:44"}}
)
resp = requests.get(
url="http://myDatabase.domain.io/api/v1/article/",
params={"q": query},
)
resp.raise_for_status()
data = resp.json()
print(data)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose i want to add something to
list = []
such that the value of list gets updated in the code it self.
In runtime:
list gets modified to
list =['hello','Dude']
How can i do so?
What i mean is, that there are real changes made to the List value in the .py file.
Judging from your comments to one of the other answers what you are looking for is a way to serialize and save an object to a file so you can reload it once you re-run the program. This is done using pickle.
An example of this can be found on stack overflow: How to save an object in Python:
import pickle
try:
with open('list.pk', 'rb') as input:
list = pickle.load(input)
except:
list = []
list.append('something')
print(list)
with open('list.pk', 'wb') as output:
pickle.dump(list, output, pickle.HIGHEST_PROTOCOL)
Just use append where ever you need it:
list = []
list.append('hello')
print list
list.append('Dude')
print list
Output:
['hello']
['hello', 'Dude']<
Easy way would be to create additional file and to store variables there.
Code:
list = []
f = open("list.txt", "r+")
for item in f:
list.append(str(item).rstrip())
f.write("Something")
f.close()
list.txt:
hello
Dude
list.txt after execution:
hello
Dude
Something
The only way to do it is rewriting the .py file.
You don't really want to do that even if it's indeed technically possible.
You should instead keep your data in a separate file, loaded when starting the program and saved back when exiting.
There are special modules for storing python values like e.g. shelve.
A very common alternative is storing the data in a format that can be understood even by other languages intead of python objects, e.g. in a relational database like sqlite.