I'm new to python and still I love it but this makes me really frustrated.
I'm trying to load 4 settings in my console app since Write.Input causing errors when converting .exe file, so I was thinking instead let user type and hit enter it would be wise to load some .JSON settings file.
I need to get all values from "amount"; "threads" etc...
My Json settings file settings.json
{ "settings_data":[
{
"amount": 1000,
"threads": 5,
"type": 1,
"id": "sK19"
}
]}
My Code:
with open(os.path.join(sys.path[0], "settings.json"), "r", encoding="utf-8") as f:
settings = json.loads(f.read())
sendTypeA = json.dumps(settings)
sendTypeB = json.loads(sendTypeA)
sendType = sendTypeB["type"]
ERROR:
Exception has occurred: KeyError
'type'
File "D:\pyprograms\main\main.py", line 38, in <module>
sendType = sendTypeB["type"]
Try the following code:
with open(os.path.join(sys.path[0], "settings.json"), "r", encoding="utf-8") as f:
settings = json.loads(f.read())
sendType = settings["settings_data"][0]["type"]
Instead of:
sendType = sendTypeB["type"]
...you need...
sendType = sendTypeB["settings_data"][0]["type"]
...because the "type" key is in a dictionary that's in the first element of the list referred to by sendTypeB["settings_data"]
Related
I am trying to read a json file, modify and then save the modified version.
Unfortunately, the content of the file, instead of being saved, adds another json to the end of the original one.
my code:
with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
test = json.load(test_file)
test['COMPONENTS'] = "test components"
json.dump(test, test_file)
test.json
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}
after running code
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
expected result:
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
Please point out what I am doing wrong
My environment
Python 3.10.9
macos 12.3.1
I try to use w+
Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0
During handling of the above exception, another exception occurred:
File "/test.py", line 20, in <module>
test = json.load(test_file)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The easiest way to do it, like UpmostScarab said, is to just open the file twice. If you only want to open it once for some reason, you can read, then seek(0), then write, and finally truncate:
with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
test = json.load(test_file)
test['COMPONENTS'] = "test components"
test_file.seek(0)
json.dump(test, test_file)
test_file.truncate()
I think the problem is adding a + to your opening modes. Also note that w+ would truncate the file, so there will be no JSON to read. I think what you should do is:
with open(os.environ.get("WORKSPACE")+"/test.json", 'r') as test_file:
test = json.load(test_file)
test['COMPONENTS'] = "test components"
with open(os.environ.get("WORKSPACE")+"/test.json", 'w') as test_file:
json.dump(test, test_file)
I want to get the dictionary below inside my data array, couldn't find much on this as most tutorials show you how to chuck variable right into the json, without ordering it into an array or object.
the JSON:
#JSON file
{
"data" :
[
]
}
the python file I want to export from:
import json
#Python file
your_facebook_info = {'name':'johhny', 'age':213, 'money':'lots'}
desired outcome:
{
"data" :
[
your_facebook_info = {
'name':'johhny',
'age':213,
'money':'lots'
}
]
}
Try this. You read the file, append the new data, write that databack to the file.
import json
#Python file
your_facebook_info = {'name':'johhny', 'age':213, 'money':'lots'}
with open('text.json','r') as inputfile:
data = json.load(inputfile)
data['data'].append(your_facebook_info)
with open("text.json", "w") as outfile:
json.dump(data, outfile)
I had a code, which gave me an empty DataFrame with no saved tweets.
I tried to debug it by putting print(line) under the for line in json file: and json_data = json.loads(line).
That resulted a KeyError.
How do I fix it?
Thank you.
list_df = list()
# read the .txt file, line by line, and append the json data in each line to the list
with open('tweet_json.txt', 'r') as json_file:
for line in json_file:
print(line)
json_data = json.loads(line)
print(line)
tweet_id = json_data['tweet_id']
fvrt_count = json_data['favorite_count']
rtwt_count = json_data['retweet_count']
list_df.append({'tweet_id': tweet_id,
'favorite_count': fvrt_count,
'retweet_count': rtwt_count})
# create a pandas DataFrame using the list
df = pd.DataFrame(list_df, columns = ['tweet_id', 'favorite_count', 'retweet_count'])
df.head()
Your comment says you're trying to save to a file, but your code kind of says that you're trying to read from a file. Here are examples of how to do both:
Writing to JSON
import json
import pandas as pd
content = { # This just dummy data, in the form of a dictionary
"tweet1": {
"id": 1,
"msg": "Yay, first!"
},
"tweet2": {
"id": 2,
"msg": "I'm always second :("
}
}
# Write it to a file called "tweet_json.txt" in JSON
with open("tweet_json.txt", "w") as json_file:
json.dump(content, json_file, indent=4) # indent=4 is optional, it makes it easier to read
Note the w (as in write) in open("tweet_json.txt", "w"). You're using r (as in read), which doesn't give you permission to write anything. Also note the use of json.dump() rather than json.load(). We then get a file that looks like this:
$ cat tweet_json.txt
{
"tweet1": {
"id": 1,
"msg": "Yay, first!"
},
"tweet2": {
"id": 2,
"msg": "I'm always second :("
}
}
Reading from JSON
Let's read the file that we just wrote, using pandas read_json():
import pandas as pd
df = pd.read_json("tweet_json.txt")
print(df)
Output looks like this:
>>> df
tweet1 tweet2
id 1 2
msg Yay, first! I'm always second :(
I am trying to write a JSON file in my python script I have the following:
#write JSON file:
data = {
'description' : 'ACME',
'taskType' : 100,
'scanFileTypes' : 542.23,
'connections' : connectionName,
'fileTypeExclude' : False,
'policies': 'PCI_Hadoop'
}
with open(jsonPropPath, 'w') as outfile:
json.dump(data, outfile, ensure_ascii=False)
My JSON file looks like:
cat /home/matt/DGagent/jsonFile_20150805102636.json
{"description": "ACME", "scanFileTypes": 542.23000000000002, "connections": "dgcl_20150805102636", "policies": "PCI_Hadoop", "taskType": 100, "fileTypeExclude": false}[matt#server1 ~]
The decimal is being extended as you can see, also its adding the server: [matt#server1 ~]
Can anyone help me correct these issues?
I want to add a new record at the end of my file Json, For now it contains
{
"1":
{
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
}
im reading this file like this :
try:
json_data=open ("/home/sage/content.txt")
data=json.load (json_data)
except IOError:
print "Can't open your file"
how to add a new record at the end of file.
After reading the data , you can't add to the file, you need to create a new file (with the same name if you want):
data['added_data'] = 'some data added'
write_file = open("/home/sage/content.txt", "w")
write_file.write(json.dumps(data))
If you are using python 2.5 or newer you should use with statement dealing with files:
import json
with open('content.txt', 'r') as f:
data = json.load(f)
data["2"] = {
"coef":987,
"Term":
{
"x1":6,"x2":0,"x3":8
}
}
with open('content.txt', 'w') as f:
json.dump(data, f)