How to dump data into Json file
*as can see in the below python code I am trying the dump data in Json file so but I am struggling to do it in python code *
import time
import json
import os
def long_function(name):
cache_path = 'cache.json'
if not os.path.isfile(cache_path):
with open(cache_path, 't') as json_file:
cache_file_data = [name]
jsondump(cache_file_data, json_file)
else:
with open(cache_path, 'r') as json_file:
cache_file_data = json.load(json_file)
if name in cache_file_data:
print("Name already exist")
return name
else:
cache_file_data.append(name)
for e in range(5):
time.sleep(1)
print(e+1)
with open(cache_path, 'w') as json_file:
jsondump(cache_file_data, json_file)
print("New Name added in cache")
return name
print(long_function('nitu'))
so please resolve my problem......please help me
import json
# JSON data:
x = '{ "organization":"New_holn",
"city":"Noida",
"country":"India"}'
# python object to be appended
y = {"pin":117845}
# parsing JSON string:
z = json.loads(x)
# appending the data
z.update(y)
# the result is a JSON string:
print(json.dumps(z))
This is nothing but follow this pattern and your so your code error is ..you are not defined file mode correctly in if condition
with open (cache_path. "t") as json_file:
Instead of
with open (cache_path. "w") as json_file:
And second thing is you are not doing dump data
Related
this is my json file
{"_index":"core-bvd-locations","_type":"_doc","_id":"75b82cba4a80784f4fa36d14c86f6d85","_score":1,"_source":{"a_id":"FR518077177","a_id_type":"BVD ID","a_name":"Moisan Patrick Roger","a_name_normal":"MOISAN PATRICK ROGER","a_country_code":"FR","a_country":"France","a_in_compliance_db":false,"a_nationality":"FR","a_street_address":"Les Carmes","a_city":"Decize","a_postcode":"58300","a_region":"Bourgogne-Franche-Comte|Nievre","a_phone":"+33 603740000","a_latitude":46.79402777777778,"a_longitude":3.496277777777778,"a_national_ids":{"European VAT number":["FR58 518077177"],"SIREN number":["518077177"],"TIN":["518077177"],"SIRET number":["518077177-00013"]},"relationship":"Location info","file_name":"/media/hedwig/iforce/data/BvD/s3-transfer/SuperTable_v3_json/locations/part-00021-1f62c713-17a0-410d-9b18-32328d9836d6-c000.json","a_geo_point":{"lat":46.79402777777778,"lon":3.496277777777778}}}
this is my code
import csv
import json
import sys
import codecs
def trans(path):
jsonData = codecs.open('F:\\1.json', 'r', 'utf-8')
# csvfile = open(path+'.csv', 'w') #
# csvfile = open(path+'.csv', 'wb') # python2
csvfile = open('F:\\1.csv', 'w', encoding='utf-8', newline='') #
writer = csv.writer(csvfile, delimiter=',')
flag = True
for line in jsonData:
dic = json.loads(line)
if flag:
keys = list(dic.keys())
print(keys)
writer.writerow(keys)
flag = False
writer.writerow(list(dic.values()))
jsonData.close()
csvfile.close()
if __name__ == '__main__':
path=str(sys.argv[0]) #
print(path)
trans(path)
C:\Users\jeri\PycharmProjects\pythonProject9\venv\Scripts\python.exe C:\Users\jeri\PycharmProjects\pythonProject9\zwc_count_file.py
C:\Users\jeri\PycharmProjects\pythonProject9\zwc_count_file.py
['_index', '_type', '_id', '_score', '_source']
Process finished with exit code 0
output jie
enter image description here
Information in nested json file cannot be parse, how can i modify the code
import json
import pandas as pd
file_data = open("json_filname.json",'r').read()
data= json.loads(file_data)
df = pd.json_normalize(data)
df
json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
import json
# Opening JSON file
f = open('data.json')
# returns JSON object as
# a dictionary
data = json.load(f)
writer.writerow write the entire row, rigth sintaxis
writer.writerow(#iterable_object#)
I have a bunch of json files with multiple lines who look like this:
file1
{"id":1,"name":"Eric","height":1.80, ...},
{"id":2,"name":"Bob","height":1.90, ...}
...
file2
{"id":3,"name":"Jenny","height":1.50, ...},
{"id":4,"name":"Marlene","height":1.60, ...}
...
I want to build a generator to yield each line as a dictionary. My current code:
from typing import Iterator, Dict, Any, Optional
import io
import os
def json_gen2(file_list: list) -> Iterator[Dict[str, Any]]:
import json
for file in file_list:
with open(file) as json_file:
data = []
for line in json_file:
data = json.load(line)
if not data:
break
yield data
datapath = os.path.normcase(os.getcwd()) + '/data/log_data'
file_list = get_files(datapath) # create path list of json files
jsonfile = json_gen2(file_list)
next(jsonfile)
i get the following
Error Message
pls help :)
Oops, I misread. You are doing the same thing I was saying. Your error is due to using 'load' instead of 'loads'. Each line returned by
for line in json_file:
data = json.load(line)
is a string, and you're attempting to read it as a file pointer.
This question already has answers here:
How to append data to a json file?
(11 answers)
Closed 3 years ago.
I have a .json file which I would like to append data to. But only if this string is not in the .json file already.
JSON File:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}]
End result JSON File:
[{"filename":"file1"}, {"filename":"file2"}, {"filename":"file3"}, {"filename":"file4"}]
I currently have this:
with open('gdrivefiles.json', 'r') as f:
filenameslist = json.load(f) #Loads the .json file into a string (If I'm right)
for distro in filenameslist:
filenames = distro["filename"] #Gets a list of all the filenames
if name in filenames:
print("yes") #If name is in the list of filenames print 'yes'
else:
print("no") #If name is in the list of filenames print 'no'
(This code is put in a for-loop, so it will run this code for every new value of name)
How would I add name ({"filename":"name"}) in the json file if it is not in it already?
This code should do what you want:
import json
new_file = {"filename":"name"}
data = json.load(open("data.json"))
if not any([new_file['filename'] == x['filename'] for x in data]):
data.append(new_file)
json.dump(data, open("data.json","w"))
You just need to create the data structure when writing back:
import json
name = "file4"
with open('gdrivefiles.json', 'r') as f:
filenameslist = json.load(f)
filenames = [distro["filename"] for distro in filenameslist]
if name in filenames:
print("yes") #If name is in the list of filenames print 'yes'
else:
print("no") #If name is in the list of filenames print 'no'
filenames.append(name)
# write filenames back to file as list of dicts!
with open('gdrivefiles.json', 'w') as f:
f.write(json.dumps([{'filename': name} for name in filenames]))
import json
new_object = {"filename":"file5"}
with open('data.json') as json_file:
data = json.load(json_file)
if new_object not in data:
data.append(new_object)
json_file.close()
with open('data.json', 'w') as outfile:
json.dump(data, outfile)
outfile.close()
I'm trying to remove the very first character (") from a file which contains a JSON String. I'm using Python for this. Below is my code:
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join(arcpy.env.scratchFolder, jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
json.dump(jsonString, json_file)
// I was able to remove the very last character using the code below
with open(jsonOutput_File, 'r+') as read_json_file:
read_json_file.seek(-1, os.SEEK_END)
read_json_file.truncate()
Basically when I dump the JSON String to a file, the String is getting surrounded by double quotes. I'm trying to remove these double quotes from the first & last position of the file.
If you already have a JSON string, simply write it to the file.
Encoding the JSON string to JSON again using json.dump() is a bad idea and will not be fixed as simple as removing a leading and a trailing quote.
Consider the following minimal and complete example:
import json
import os
import uuid
myobject = {"hello": "world"}
jsonString = json.dumps(myobject)
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
json.dump(jsonString, json_file)
The output is a file with the content:
"{\"hello\": \"world\"}"
Removing the quotes will not make it valid JSON.
Instead, avoid the duplicate JSON creation, either by removing json.dumps() which converts the object to JSON one time, or by removing json.dump(), which does it a second time.
Solution 1:
import json
import os
import uuid
myobject = {"hello": "world"}
# <-- deleted line here
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
json.dump(myobject, json_file) # <-- changed to object here
Solution 2:
import json
import os
import uuid
myobject = {"hello": "world"}
jsonString = json.dumps(myobject)
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
json_file.write(jsonString) # <-- Note this line
So I'm trying to setup json so i can store data in-between user sessions I like a name but i don't know how to add or change a specific value in an external json file like for example {"name": ""} how do i fill that "" for the json file using python?
I have already tried to use dumps and all the tutorials use dumps
the json in another file
{
"human_name": "",
"oracle_name": "",
"human_age": "",
"human_gender": "",
"oracle_gender": ""
}
the python
import json
with open('data.json', '+') as filedata:
data = filedata.read()
used_data = json.loads(data)
if str(used_data(['human_name'])) == "":
print("what is your name")
name = input()
json.dumps(name)
if str(used_data(['oracle_name'])) == "":
print("what is my name")
oracle_name = input()
json.dumps(oracle_name)
print(str(['human_name']))
The expected result is when I print the data it displays input, but when i run it it goes
File "rember.py", line 3, in
with open('data.json', '+') as filedata: ValueError: Must have exactly one of create/read/write/append mode and at most one plus
Try this code.
json.loads loads the entire json string as a python dict object. The values in a dict are changed/added using dict[key] = value. You can't call a dict object to change its value.
The json.dumps method serializes an object to a JSON formatted str. Which you can then write into the same file or a different file based on your requirement.
import json
with open('data.json', 'r') as filedata:
data = filedata.read()
used_data = json.loads(data)
if used_data['human_name'] == "":
print("what is your name")
name = input()
used_data['human_name'] = name
if used_data['oracle_name'] == "":
print("what is my name")
oracle_name = input()
used_data['oracle_name'] = oracle_name
print(used_data)
with open('data.json', 'w') as filewrite:
filewrite.write(json.dumps(used_data, indent=4))
Basically what you need to do is load json file as dictionary, add value, and save it.
import json
with open('./data.json', 'r') as f:
d = json.load(f)
d['human_name'] = 'steve'
d['oracle_name'] = 'maria'
with open('./data.json', 'w') as f:
json.dump(d, f, indent=4)