Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Đọc
Bàn luận
- Hình thức đầy đủ của JSON là ký hiệu đối tượng JavaScript. Điều đó có nghĩa là một tệp tập lệnh [thực thi] được tạo bằng văn bản bằng ngôn ngữ lập trình, được sử dụng để lưu trữ và chuyển dữ liệu. Python hỗ trợ JSON thông qua gói tích hợp có tên JSON. Để sử dụng tính năng này, chúng tôi nhập gói JSON trong tập lệnh Python. Văn bản trong JSON được thực hiện thông qua chuỗi trích dẫn có chứa giá trị trong ánh xạ giá trị khóa trong {}. & Nbsp; & nbsp;json.loads[] function is present in python built-in ‘json’ module. This function is used to parse the JSON
string.
Các chức năng được sử dụng: & nbsp; & nbsp; json.loads[json_string]
Parameter: It takes JSON string as the parameter.
Return type: It returns the python dictionary object.
- json.loads []: hàm json.loads [] có mặt trong mô-đun python tích hợp ‘json. Hàm này được sử dụng để phân tích chuỗi JSON. & NBSP;json.dumps[] function is present in python built-in ‘json’ module. This function is used to convert Python object into JSON string.
Cú pháp: tham số JSON.LOADS [JSON_STRING]: Nó lấy chuỗi JSON làm tham số.return loại: nó trả về đối tượng từ điển Python. & Nbsp; & nbsp; json.dumps[object]
Parameter: It takes Python Object as the parameter.
Return type: It returns the JSON string.
- json.dumps []: hàm json.dumps [] có mặt trong mô-đun python tích hợp ‘json. Hàm này được sử dụng để chuyển đổi đối tượng Python thành Chuỗi JSON. & NBSP; This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
Cú pháp: json.dumps [Đối tượng] Tham số: Nó lấy đối tượng Python làm tham số.return loại: nó trả về chuỗi JSON. & Nbsp; & nbsp; dict.update[[other]]
Parameters: Takes another dictionary or an iterable key/value pair.
Return type: Returns None.
CẬP NHẬT []: Phương thức này cập nhật từ điển với các phần tử từ một đối tượng từ điển khác hoặc từ một cặp khóa/giá trị có thể lặp lại. & NBSP; Updating a JSON string.
Python3
Cú pháp: Dict.Update [[Khác]] Tham số: Lấy một từ điển khác hoặc một cặp khóa/giá trị có thể lặp lại.
Ví dụ 1: Cập nhật chuỗi JSON. & NBSP; & NBSP;
with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
2with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
3def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
5with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
1with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
2with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
8def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
0with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
1def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
3 def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
4________ 15 ________ 16 & nbsp;
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
7def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
8def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
0with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
1with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
2def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
6 with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
4with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
5def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
7with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
8with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append[entry]
json.dump[feeds, feedsjson]
3with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append[entry]
json.dump[feeds, feedsjson]
4Output:
9with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f: json.dump[[], f]
6def add[args]: with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson: feeds = json.load[feedsjson] with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson: entry = {} entry['name'] = args.name entry['url'] = args.url json.dump[entry, feedsjson]
1with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson: entry = {'name': args.name, 'url': args.url} feeds.append[entry] json.dump[feeds, feedsjson]
2 Updating a JSON file. Suppose the JSON file looks like this.with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append[entry]
json.dump[feeds, feedsjson]
{Pin Pin Cảnh: 110096, Tổ chức của người Hồi giáo
Python3
Cú pháp: Dict.Update [[Khác]] Tham số: Lấy một từ điển khác hoặc một cặp khóa/giá trị có thể lặp lại.
Ví dụ 1: Cập nhật chuỗi JSON. & NBSP; & NBSP;
a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
2a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
3a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
4a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
5a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
6a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
7a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
8def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
3 def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
4with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
2import json
def append_to_json[_dict,path]:
with open[path, 'ab+'] as f:
f.seek[0,2] #Go to the end of file
if f.tell[] == 0 : #Check if file is empty
f.write[json.dumps[[_dict]].encode[]] #If empty, write an array
else :
f.seek[-1,2]
f.truncate[] #Remove the last character, open the array
f.write[' , '.encode[]] #Write the separator
f.write[json.dumps[_dict].encode[]] #Dump the dictionary
f.write[']'.encode[]] #Close the array
7import json
def append_to_json[_dict,path]:
with open[path, 'ab+'] as f:
f.seek[0,2] #Go to the end of file
if f.tell[] == 0 : #Check if file is empty
f.write[json.dumps[[_dict]].encode[]] #If empty, write an array
else :
f.seek[-1,2]
f.truncate[] #Remove the last character, open the array
f.write[' , '.encode[]] #Write the separator
f.write[json.dumps[_dict].encode[]] #Dump the dictionary
f.write[']'.encode[]] #Close the array
8import json
def append_to_json[_dict,path]:
with open[path, 'ab+'] as f:
f.seek[0,2] #Go to the end of file
if f.tell[] == 0 : #Check if file is empty
f.write[json.dumps[[_dict]].encode[]] #If empty, write an array
else :
f.seek[-1,2]
f.truncate[] #Remove the last character, open the array
f.write[' , '.encode[]] #Write the separator
f.write[json.dumps[_dict].encode[]] #Dump the dictionary
f.write[']'.encode[]] #Close the array
9with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
2a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
8with open['file.json', 'a'] as outfile:
outfile.write[json.dumps[data]]
outfile.write[","]
outfile.close[]
2with open['file.json', 'a'] as outfile:
outfile.write[json.dumps[data]]
outfile.write[","]
outfile.close[]
3import json
def append_to_json[_dict,path]:
with open[path, 'ab+'] as f:
f.seek[0,2] #Go to the end of file
if f.tell[] == 0 : #Check if file is empty
f.write[json.dumps[[_dict]].encode[]] #If empty, write an array
else :
f.seek[-1,2]
f.truncate[] #Remove the last character, open the array
f.write[' , '.encode[]] #Write the separator
f.write[json.dumps[_dict].encode[]] #Dump the dictionary
f.write[']'.encode[]] #Close the array
5________ 15 ________ 16 & nbsp;
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
7def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
8def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
0with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
1with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
2def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
6 with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
4with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
5def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
9with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
7with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
8# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile[fname]:
# File exists
with open[fname, 'a+'] as outfile:
outfile.seek[-1, os.SEEK_END]
outfile.truncate[]
outfile.write[',']
json.dump[data_dict, outfile]
outfile.write[']']
else:
# Create file
with open[fname, 'w'] as outfile:
array = []
array.append[data_dict]
json.dump[array, outfile]
9import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
0import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
1import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
2with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
1# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile[fname]:
# File exists
with open[fname, 'a+'] as outfile:
outfile.seek[-1, os.SEEK_END]
outfile.truncate[]
outfile.write[',']
json.dump[data_dict, outfile]
outfile.write[']']
else:
# Create file
with open[fname, 'w'] as outfile:
array = []
array.append[data_dict]
json.dump[array, outfile]
9import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
5import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
1import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
7a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
2with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
8def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
00Output:
Đẩy [Newdata]; Để viết dữ liệu mới này vào tệp JSON của chúng tôi, chúng tôi sẽ sử dụng FS. WriteFile [] lấy tệp JSON và dữ liệu được thêm vào làm tham số. Lưu ý rằng trước tiên chúng ta sẽ phải chuyển đổi đối tượng trở lại định dạng RAW trước khi viết nó.
[{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}]
Làm cách nào để cập nhật một trường trong JSON?
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
Để cập nhật dữ liệu JSON trong bảng: Truy vấn và truy xuất dữ liệu JSON từ cột JSON. Sửa đổi nội dung của cột JSON. Để đẩy giá trị cột được cập nhật trở lại vào bảng, hãy đưa ra câu lệnh SQL cập nhật và chỉ định hàm JSON2BSON.
Tôi đang cố gắng tạo một chức năng sẽ thêm các mục vào tệp JSON. Cuối cùng, tôi muốn một tệp trông giống như: The first answers and comments to this question have pointed out the obvious fact that I am not using
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
03 in the write block. I don't see how to do that, though. For example, the following apparently will not do:with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
v.v ... Đây là những gì tôi có:
Điều này không tạo ra một mục như
01. Nhưng, nếu tôi sử dụng chức năng def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
02 này một lần nữa, với tên và URL khác nhau, thì bản đầu tiên bị ghi đè. Tôi cần làm gì để có được mục nhập thứ hai [thứ ba ...] được thêm vào lần đầu tiên?25 gold badges160 silver badges284 bronze badgesdef add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
Chỉnh sửa: Câu trả lời và nhận xét đầu tiên cho câu hỏi này đã chỉ ra một thực tế rõ ràng rằng tôi không sử dụng
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
03 trong khối ghi. Tôi không thấy làm thế nào để làm điều đó, mặc dù. Ví dụ, những điều sau đây rõ ràng sẽ không làm:Oct 21, 2012 at 2:35
3
Martineau
Huy hiệu vàng 116K25
Hỏi ngày 21 tháng 10 năm 2012 lúc 2:35
JSON có thể không phải là lựa chọn tốt nhất cho các định dạng trên đĩa; Rắc rối mà nó gặp phải với dữ liệu nối tiếp là một ví dụ tốt về lý do tại sao điều này có thể. Cụ thể, các đối tượng JSON có cú pháp có nghĩa là toàn bộ đối tượng phải được đọc và phân tích cú pháp để hiểu bất kỳ phần nào của nó.Oct 21, 2012 at 3:08
5
May mắn thay, có rất nhiều lựa chọn khác. Một đặc biệt đơn giản là CSV; được hỗ trợ tốt bởi thư viện tiêu chuẩn của Python. Nhược điểm lớn nhất là nó chỉ hoạt động tốt cho văn bản; Nó yêu cầu hành động bổ sung về phía người lập trình để chuyển đổi các giá trị thành số hoặc các định dạng khác, nếu cần.
Một tùy chọn khác không có giới hạn này là sử dụng cơ sở dữ liệu SQLite, cũng có hỗ trợ tích hợp trong Python. Đây có lẽ sẽ là một sự khởi đầu lớn hơn từ mã bạn đã có, nhưng nó tự nhiên hỗ trợ mô hình 'sửa đổi một chút' mà bạn dường như đang cố gắng xây dựng.
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
json.dump[[], f]
Sau đó, bạn có thể nối các mục mới vào danh sách này:
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {'name': args.name, 'url': args.url}
feeds.append[entry]
json.dump[feeds, feedsjson]
Lưu ý rằng điều này sẽ chậm thực thi vì bạn sẽ viết lại toàn bộ nội dung của tệp mỗi khi bạn gọi
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
02. Nếu bạn đang gọi nó trong một vòng lặp, hãy xem xét thêm tất cả các nguồn cấp dữ liệu vào một danh sách trước, sau đó viết danh sách trong một lần.Đã trả lời ngày 21 tháng 10 năm 2012 lúc 2:54Oct 21, 2012 at 2:54
Nneonneonneonneonneonneo
166K35 Huy hiệu vàng297 Huy hiệu bạc368 Huy hiệu Đồng35 gold badges297 silver badges368 bronze badges
6
Nối vào mục nhập vào nội dung tệp nếu tệp tồn tại, nếu không hãy nối phần nhập vào một danh sách trống và ghi vào tệp:
a = []
if not os.path.isfile[fname]:
a.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[a, indent=2]]
else:
with open[fname] as feedsjson:
feeds = json.load[feedsjson]
feeds.append[entry]
with open[fname, mode='w'] as f:
f.write[json.dumps[feeds, indent=2]]
Đã trả lời ngày 6 tháng 3 năm 2016 lúc 17:35Mar 6, 2016 at 17:35
NargesootvnargesootvNargesooTv
7727 Huy hiệu bạc14 Huy hiệu đồng7 silver badges14 bronze badges
2
Sử dụng
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
05 thay vì def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
06 sẽ cho phép bạn cập nhật tệp thay vì tạo một/ghi đè mọi thứ mới trong tệp hiện có.Xem câu trả lời này để biết sự khác biệt trong các chế độ.
Đã trả lời ngày 21 tháng 10 năm 2012 lúc 2:42Oct 21, 2012 at 2:42
Susan Wrightsusan WrightSusan Wright
3961 Huy hiệu vàng3 Huy hiệu bạc13 Huy hiệu đồng1 gold badge3 silver badges13 bronze badges
7
Một giải pháp khả thi là làm cách thủ công, đây là một số mã hữu ích:
import json
def append_to_json[_dict,path]:
with open[path, 'ab+'] as f:
f.seek[0,2] #Go to the end of file
if f.tell[] == 0 : #Check if file is empty
f.write[json.dumps[[_dict]].encode[]] #If empty, write an array
else :
f.seek[-1,2]
f.truncate[] #Remove the last character, open the array
f.write[' , '.encode[]] #Write the separator
f.write[json.dumps[_dict].encode[]] #Dump the dictionary
f.write[']'.encode[]] #Close the array
Bạn nên cẩn thận khi chỉnh sửa tệp bên ngoài tập lệnh không thêm bất kỳ khoảng cách nào ở cuối.
Đã trả lời ngày 17 tháng 6 năm 2017 lúc 1:23Jun 17, 2017 at 1:23
SedaradjisedaradjiSEDaradji
1.23713 huy hiệu bạc18 Huy hiệu đồng13 silver badges18 bronze badges
2
Điều này, làm việc cho tôi:
with open['file.json', 'a'] as outfile:
outfile.write[json.dumps[data]]
outfile.write[","]
outfile.close[]
Đã trả lời ngày 21 tháng 12 năm 2019 lúc 12:51Dec 21, 2019 at 12:51
hassanzadeh.sdhassanzadeh.sdhassanzadeh.sd
2.7431 Huy hiệu vàng15 Huy hiệu bạc23 Huy hiệu đồng1 gold badge15 silver badges23 bronze badges
Bạn không bao giờ viết bất cứ điều gì để làm với dữ liệu bạn đọc. Bạn có muốn thêm cấu trúc dữ liệu vào nguồn cấp dữ liệu vào dữ liệu mới mà bạn đang tạo không?
Hoặc có lẽ bạn muốn mở tệp ở chế độ nối
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
07 và sau đó thêm chuỗi của bạn, bằng cách viết chuỗi được tạo bởi def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
08 thay vì sử dụng def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
09 - nhưng Nneonneo chỉ ra rằng đây sẽ là JSON không hợp lệ.Đã trả lời ngày 21 tháng 10 năm 2012 lúc 2:38Oct 21, 2012 at 2:38
ThomasthomasThomas
6.3181 Huy hiệu vàng28 Huy hiệu bạc45 Huy hiệu đồng1 gold badge28 silver badges45 bronze badges
2
Tôi có một số mã tương tự, nhưng không viết lại toàn bộ nội dung mỗi lần. Điều này có nghĩa là chạy định kỳ và nối một mục nhập JSON ở cuối một mảng.
Nếu tệp chưa tồn tại, nó sẽ tạo nó và đổ JSON vào một mảng. Nếu tệp đã được tạo, nó sẽ đi đến cuối, thay thế
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
10 bằng một with open[DATA_FILENAME, mode='a+', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feeds]
1 sẽ thả đối tượng JSON mới vào, sau đó đóng lại với một def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
10 khác với một def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
10 khác# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile[fname]:
# File exists
with open[fname, 'a+'] as outfile:
outfile.seek[-1, os.SEEK_END]
outfile.truncate[]
outfile.write[',']
json.dump[data_dict, outfile]
outfile.write[']']
else:
# Create file
with open[fname, 'w'] as outfile:
array = []
array.append[data_dict]
json.dump[array, outfile]
Đã trả lời ngày 14 tháng 11 năm 2018 lúc 23:35Nov 14, 2018 at 23:35
MattmattMatt
2713 Huy hiệu bạc9 Huy hiệu Đồng3 silver badges9 bronze badges
1
import jsonlines
object1 = {
"name": "name1",
"url": "url1"
}
object2 = {
"name": "name2",
"url": "url2"
}
# filename.jsonl is the name of the file
with jsonlines.open["filename.jsonl", "a"] as writer: # for writing
writer.write[object1]
writer.write[object2]
with jsonlines.open['filename.jsonl'] as reader: # for reading
for obj in reader:
print[obj]
Truy cập để biết thêm thông tin //jsonlines.readthedocs.io/en/latest/
Đã trả lời ngày 1 tháng 2 năm 2021 lúc 14:50Feb 1, 2021 at 14:50
Bạn có thể chỉ cần nhập dữ liệu từ tệp nguồn, đọc nó và lưu những gì bạn muốn nối vào một biến. Sau đó, mở tệp đích, gán dữ liệu danh sách bên trong cho một biến mới [có lẽ tất cả sẽ là JSON hợp lệ], sau đó sử dụng chức năng 'nối' trên biến danh sách này và nối biến đầu tiên vào nó. Viola, bạn đã thêm vào danh sách JSON. Bây giờ chỉ cần ghi đè tệp đích của bạn với danh sách mới được thêm vào [dưới dạng JSON].
Chế độ 'A' trong hàm 'mở' của bạn sẽ không hoạt động ở đây vì nó sẽ chỉ giải quyết mọi thứ vào cuối tệp, điều này sẽ khiến nó không định dạng JSON không phải là Valid.
Đã trả lời ngày 29 tháng 6 năm 2020 lúc 19:34Jun 29, 2020 at 19:34
ToakleytoakleyToakley
671 Huy hiệu bạc10 Huy hiệu đồng1 silver badge10 bronze badges
Giả sử bạn có các dicts sau đây
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
0Bạn có thể biến điều này thành một JSON kết hợp như thế này:
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
1Do đó, mã để nối vào tệp JSON sẽ trông giống như bên dưới:
def add[args]:
with open[DATA_FILENAME, mode='r', encoding='utf-8'] as feedsjson:
feeds = json.load[feedsjson]
with open[DATA_FILENAME, mode='w', encoding='utf-8'] as feedsjson:
entry = {}
entry['name'] = args.name
entry['url'] = args.url
json.dump[entry, feedsjson]
2Đã trả lời ngày 30 tháng 5 lúc 6:15May 30 at 6:15