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
Related
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 last year.
Improve this question
What is the code required to print the ContractName sub category (under result) ?
I know to get result I have my dictionary result :
response_dict = response.json()
print()response_dict["result"]
But how do I get ContractName??
{
"status":"1",
"message":"OK",
"result":[
{
"SourceCode":"test",
"ContractName":"DAO",
"CompilerVersion":"v0.3.1-2016-04-12-3ad5e82",
}
]
}
The value of result in your dictionary is a list. That list, in your example, contains one element which is another dictionary.
Therefore:
response_dict['result'][0]['ContractName']
...will give you what you need.
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 1 year ago.
Improve this question
I'm new to Python, and I'm trying to store data in a .json, and then access and modify it through Python. Currently I'm having an issue where I can't modify the data if I try to use a variable instead of directly modifying it. It works fine if it's not in a variable, or if I'm just reading the information, or if it's not in a function.
import json
with open('testprog.json', 'r+') as f:
data = json.load(f)
x = int(data['valueOne'])
def test():
x += 1
#VSC tells me this variable is not defined.
#If I swap the variable for “int(data[‘valueOne’])” it works.
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()
test()
print("New first value is: "+str(data['valueOne']))
.json:
{
"valueOne": 10,
"valueTwo": 5,
"valueThree": 8
}
I assume that the value associated with the key valueOne is a string. Therefore you could do this:
data['valueOne'] = str(int(data['valueOne']) + 1)
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)
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 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 3 years ago.
Improve this question
(UPDATED): Added code to match values according to their ids. Question: Why are the matching ids u'1' and 'u'0' in both dictionaries not recognized?
(GOAL for Code):
I'm writing a script that takes commented text from a .docx file and matches it to comments via xml tag ids. I've managed to extract the comment tags, text and ids. I now need to match these up. My strategy is to create two dictionaries: 1) one with the ids as keys and the commented text as values and 2) the second with ids as keys and the comments as values.
Then I plan to run through both dictionaries and if their keys (i.e. ids) match up, I want to make tuples of matching commented text/comment pairs. I'm having trouble creating a dictionary and I'm getting the error message that my syntax for creating the dictionary is invalid. I don't quite understand why. Any ideas?
from bs4 import BeautifulSoup as Soup
f = open('transcript.xml','r')
soup = Soup(f)
#print soup.prettify()
textdict = {}
for i in soup.find_all('w:commentrangestart'):
# variable 'key' is assigned to the tag id
key = i.parent.contents[1].attrs['w:id']
#variable 'value' is assigned to the tag's text
value= ''.join(i.nextSibling.findAll(text=True)
# key / value pairs are added to the dictionary 'text_d'
textdict[key]=value
print textdict
commentdict = {}
for i in soup.find_all('w:comment'):
key = i.attrs['w:id']
value= ''.join(i.findAll(text=True)
commentdict[key]=value
print commentdict
## OUTPUT {u'1': u'contradictory about news', u'0': u'something about news'}
## {u'1': u'News; comment; negative', u'0': u'News; comment'}
## Added Code
for key in set(textdict) & set (commentdict):
if textdict[key] == commentdict[key]:
print 'yay'
You have a syntax error because you didn't close a parenthesis:
value= ''.join(i.nextSibling.findAll(text=True)
# -------------^ missing )
You are missing another a few lines further on too:
value= ''.join(i.findAll(text=True)
# -------------^ missing )