Hướng dẫn how do i add data to an existing json object in python? - làm cách nào để thêm dữ liệu vào một đối tượng json hiện có trong python?

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • 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]
    
    2
    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]
    
    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]
    
    9
    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]
    
    5
    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

    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]
    
    2
    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]
    
    8
    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]
    
    9
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    0
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    1

    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]
    
    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]
    
    7
    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]
    
    8
    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]
    
    9
    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]
    
    0
    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

    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    2
    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]
    
    6
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    4
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    5
    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]
    
    9
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    7
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    8

    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]
    
    3
    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]
    
    4

    Output: 
     

    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    9
    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]
    
    6
    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]
    
    1
     

    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]
    
    2 Updating a JSON file. Suppose the JSON file looks like this.
     

    {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]]
    
    2
    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]]
    
    3
    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]]
    
    4
    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]]
    
    5
    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]]
    
    6
    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]]
    
    7
    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]]
    
    8
    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]
    
    9

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

    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]
    
    2
    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
    
    7
    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
    
    8
    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
    
    9

    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]
    
    2
    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]]
    
    8
    with open['file.json', 'a'] as outfile:
        outfile.write[json.dumps[data]]
        outfile.write[","]
        outfile.close[]
    
    2
    with open['file.json', 'a'] as outfile:
        outfile.write[json.dumps[data]]
        outfile.write[","]
        outfile.close[]
    
    3
    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
    
    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]
    
    7
    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]
    
    8
    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]
    
    9
    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]
    
    0
    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

    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    2
    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]
    
    6
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    4
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    5
    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]
    
    9
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    7
    with 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]
    
    9
    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]             
    
    0
    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]             
    
    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]             
    
    2
    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

    # 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]
    
    9
    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]             
    
    5
    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]             
    
    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]             
    
    7

    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]]
    
    2
    with open[DATA_FILENAME, mode='w', encoding='utf-8'] as f:
        json.dump[[], f]
    
    8

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

    Output: 
     


    79

    Thực hiện theo quy trình tương tự là tạo tệp đích JSON bằng cách sử dụng thao tác Chèn tác vụ để cập nhật tệp JSON hiện có ..
    Learn more.

    Làm cách nào để ghi dữ liệu vào tệp JSON?

    [{"name" = "name1", "url" = "url1"}, {"name" = "name2", "url" = "url2"}]
    

    Đầu tiên, để ghi dữ liệu vào tệp JSON, chúng ta phải tạo chuỗi JSON của dữ liệu với JSON.Stringify. Điều này trả về một biểu diễn chuỗi JSON của một đối tượng JavaScript, có thể được ghi vào một tệp.

    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]
    

    Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.

    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ư

    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]
    
    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 badges285 bronze badges

    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

    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.

    Đã trả lời ngày 21 tháng 10 năm 2012 lúc 3:08Oct 21, 2012 at 3:08

    5

    Bạn có thể muốn sử dụng danh sách JSON thay vì từ điển làm yếu tố Toplevel.

    Vì vậy, hãy khởi tạo tệp với một danh sách trố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.24713 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.7631 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]
    
    0

    Bạ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]
    
    1

    Do đó, 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

    Làm cách nào để thêm dữ liệu vào đối tượng JSON hiện có?

    Làm thế nào để bạn thêm dữ liệu vào một đối tượng JSON hiện có trong Node JS ?..
    Chèn dữ liệu JSON mới vào tệp JSON bằng NodeJS ..
    Nối đối tượng JavaScript vào tệp JSON ..
    Thay thế một ký tự trong một tệp bằng nút js ..
    Phương pháp foreach bỏ qua các đối tượng trong khi lặp lại ..
    Thêm đối tượng vào JSON với nút ..

    Làm thế nào để bạn cập nhật một đối tượng JSON trong Python?

    Cách cập nhật tệp JSON trong Python..
    a_file = open ["sample_file.json", "r"].
    json_Object = json.tải [a_file].
    một tập tin.gần[].
    print[json_object].
    json_object ["d"] = 100 ..
    a_file = open ["sample_file.json", "w"].
    json.Dump [json_Object, a_file].
    một tập tin.gần[].

    Làm cách nào để cập nhật tệp JSON hiện có?

    Cập nhật hoặc hợp nhất tệp JSON hiện có..
    Tạo một cái mới.nhiệm vụ..
    Trong.Sự định nghĩa.Tab, chọn.Cập nhật.như hoạt động nhiệm vụ ..
    Thực hiện theo quy trình tương tự là tạo tệp đích JSON bằng cách sử dụng thao tác Chèn tác vụ để cập nhật tệp JSON hiện có ..

    Làm cách nào để ghi dữ liệu vào tệp JSON?

    Đầu tiên, để ghi dữ liệu vào tệp JSON, chúng ta phải tạo chuỗi JSON của dữ liệu với JSON.Stringify.Điều này trả về một biểu diễn chuỗi JSON của một đối tượng JavaScript, có thể được ghi vào một tệp.create a JSON string of the data with JSON. stringify . This returns a JSON string representation of a JavaScript object, which can be written to a file.

    Bài Viết Liên Quan

    Chủ Đề