Python JSON File Writing - python

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?

Related

How to get string of JSON settings in Python

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"]

Converting CSV to jSON - Keep getting "End of File expected" error

I'm trying to convert a CSV file into a jSON file in order to then inject it into a Firebase database.
csvfile = open('final_df_2.csv', 'r')
jsonfile = open('final_df_5.json', 'w')
reader = csv.DictReader(csvfile)
for row in reader:
json.dump({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]}, jsonfile)
jsonfile.write('\n')
Unfortunately, I keep getting an "End of File expected" error
Here's my JSON's output
{
"001": [
{
"colour": "green",
"radius": "199405.0"
}
]
}
{
"002": [
{
"colour": "blue",
"radius": "199612.0"
}
]
}
In addition, Firebase sends back an error when I try to import the JSON file saying "Invalid JSON files"
You could collect all the data into a python list and dump that list to the json file:
csvfile = open('final_df_2.csv', 'r')
reader = csv.DictReader(csvfile)
jsoncontent = []
for row in reader:
jsoncontent.append({row['ballID']: [{"colour": row['colour'], "radius":row['radius']}]})
with open('final_df_5.json', 'w') as jsonfile:
json.dump(jsoncontent, jsonfile)
However, I'm not sure what your firebase database is expecting.

How can I export a dictionary inside a list that's already in a JSON file? | Python

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)

Trouble with this error while adding a dict to an existing key value

Code Including JSON File Code:
Python( Suppose To Append A New User and Balance):
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)['user_list']
data['user_list']
data.append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)
Json(Object The Code Is Appending To):
{
"user_list": [
{
"user": "<#!672986823185661955>",
"balance": 400
},
{
"user": "<#!737747404048171043>",
"balance": 500
}
],
}
Error(Traceback Error Given After Executing Code):
data = json.load(file)['user_list']
KeyError: 'user_list'
The solution is this:
import json
with open('users_balance.json', 'r') as file:
data = json.load(file)
data['user_list'].append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)

KeyError occures while opening the JSON txt file and setting it up into a DataFrame

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 :(

Categories