Hướng dẫn python json add key-value pair - python json thêm cặp khóa-giá trị

Tôi chưa quen với Python và tôi đang chơi với dữ liệu JSON. Tôi muốn lấy dữ liệu JSON từ một tệp và thêm vào dữ liệu đó là giá trị khóa JSON "Khi đang bay".

Đó là, json_file của tôi chứa dữ liệu JSON giống như sau:

{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

Tôi muốn thêm phần giá trị khóa "ADDED_KEY": "ADDED_VALUE" vào dữ liệu trên để sử dụng JSON sau trong tập lệnh của tôi:

{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}

Tôi đang cố gắng viết một cái gì đó giống như sau đây để thực hiện những điều trên:

import json

json_data = open(json_file)
json_decoded = json.load(json_data)

# What I have to make here?!

json_data.close()

Hướng dẫn python json add key-value pair - python json thêm cặp khóa-giá trị

Martineau

Huy hiệu vàng 116K2525 gold badges160 silver badges285 bronze badges

Hỏi ngày 16 tháng 4 năm 2014 lúc 13:58Apr 16, 2014 at 13:58

Đối tượng

{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
0 của bạn là một từ điển Python; Bạn có thể chỉ cần thêm khóa của mình vào đó, sau đó mã lại và viết lại tệp:

import json

with open(json_file) as json_file:
    json_decoded = json.load(json_file)

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

with open(json_file, 'w') as json_file:
    json.dump(json_decoded, json_file)

Tôi đã sử dụng các đối tượng tệp mở làm Trình quản lý ngữ cảnh ở đây (với câu lệnh

{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
1) để Python tự động đóng tệp khi hoàn thành.

Đã trả lời ngày 16 tháng 4 năm 2014 lúc 14:01Apr 16, 2014 at 14:01

Martijn Pieters ♦ Martijn PietersMartijn Pieters

994K277 Huy hiệu vàng3915 Huy hiệu bạc3259 Huy hiệu đồng277 gold badges3915 silver badges3259 bronze badges

2

JSON trở về từ json.loads () hoạt động giống như danh sách/từ điển python bản địa:

import json

with open("your_json_file.txt", 'r') as f:
    data = json.loads(f.read()) #data becomes a dictionary

#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'

#and then just write the data back on the file
with open("your_json_file.txt", 'w') as f:
    f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
#I added some options for pretty printing, play around with them!

Để biết thêm thông tin, hãy xem tài liệu chính thức

Đã trả lời ngày 16 tháng 4 năm 2014 lúc 14:38Apr 16, 2014 at 14:38

0xff0xff0xff

Phù hiệu bằng đồng 11122 bronze badges

Bạn có thể làm

json_decoded['ADDED_KEY'] = 'ADDED_VALUE'

HOẶC

json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})

hoạt động độc đáo nếu bạn muốn thêm nhiều hơn một cặp khóa/giá trị.

Tất nhiên, bạn có thể muốn kiểm tra sự tồn tại của thêm_Key trước - phụ thuộc vào nhu cầu của bạn.

Và tôi giả sử bạn muốn có thể muốn lưu dữ liệu đó trở lại tệp

json.dump(json_decoded, open(json_file,'w'))

Đã trả lời ngày 16 tháng 4 năm 2014 lúc 14:09Apr 16, 2014 at 14:09

BSOISTBSOISTbsoist

7653 Huy hiệu bạc10 Huy hiệu đồng3 silver badges10 bronze badges

3

Cách thêm một phần tử vào đối tượng JSON trong Python.

Fruit_json = {"Apple": 1, "Orange": 2}.

khóa = "chuối".

  • Giá trị = 3 ..
  • Fruit_json [khóa] = giá trị ..
  • Cách thêm một phần tử vào đối tượng JSON trong Python.

    Fruit_json = {"Apple": 1, "Orange": 2}.

    khóa = "chuối".

    Giá trị = 3 ..
     

    Các chức năng được sử dụng: & nbsp; & nbsp;  

    • 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.loads() function is present in python built-in ‘json’ module. This function is used to parse the 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.loads(json_string)
    Parameter: It takes JSON string as the parameter.
    Return type: It returns the python dictionary object. 
     

    • 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;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: 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; json.dumps(object)
    Parameter: It takes Python Object as the parameter.
    Return type: It returns the JSON string. 
     

    • 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; This method updates the dictionary with elements from another dictionary object or from an iterable key/value pair.
       

    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. dict.update([other])
    Parameters: Takes another dictionary or an iterable key/value pair.
    Return type: Returns None. 
     

    Ví dụ 1: Cập nhật chuỗi JSON. & NBSP; & NBSP; Updating a JSON string.
      

    Python3

    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    2
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    3

    ________ 14 ________ 15 & nbsp;

    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    6
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    7
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    9
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    0

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    1
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    2
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    4
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    0

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    1
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    7
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    9
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    0

    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    1
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    5
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    3
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    4
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    6
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    7

    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    8
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    5
    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    0

    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    1

    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    2
    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    3

    Output: 
     

    {Pin Pin Cảnh: 110096, Tổ chức của người Hồi giáo
     

    Ví dụ 2: Cập nhật tệp JSON. Giả sử tệp JSON trông như thế này. & NBSP; Updating a JSON file. Suppose the JSON file looks like this.
     

    Hướng dẫn python json add key-value pair - python json thêm cặp khóa-giá trị

    Chúng tôi muốn thêm một dữ liệu JSON khác sau EMP_DETAILS. Dưới đây là việc thực hiện.

    Python3

    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    2
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    3

    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    6
    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    7
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    5
    import json
    
    with open("your_json_file.txt", 'r') as f:
        data = json.loads(f.read()) #data becomes a dictionary
    
    #do things with data here
    data['ADDED_KEY'] = 'ADDED_VALUE'
    
    #and then just write the data back on the file
    with open("your_json_file.txt", 'w') as f:
        f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    #I added some options for pretty printing, play around with them!
    
    9
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    0

    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    1
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    2
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    3
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    4
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    5
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    6
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    7
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    1
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    0
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    5
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    2
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    7
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    4

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    1
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    6
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    7
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    8

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    1
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    7
    json.dump(json_decoded, open(json_file,'w'))
    
    1
    json.dump(json_decoded, open(json_file,'w'))
    
    2
    json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
    
    4

    Các

    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    1
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    5
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    3json_file4
    {"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
    
    8json_file6
    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    0

    json_file8json_file9"ADDED_KEY": "ADDED_VALUE"0"ADDED_KEY": "ADDED_VALUE"1

    import json
    
    json_data = open(json_file)
    json_decoded = json.load(json_data)
    
    # What I have to make here?!
    
    json_data.close()
    
    0

    json_file8"ADDED_KEY": "ADDED_VALUE"4"ADDED_KEY": "ADDED_VALUE"0"ADDED_KEY": "ADDED_VALUE"6

    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    1
    import json
    
    with open(json_file) as json_file:
        json_decoded = json.load(json_file)
    
    json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
    
    with open(json_file, 'w') as json_file:
        json.dump(json_decoded, json_file)
    
    7

    "ADDED_KEY": "ADDED_VALUE"9

    Output: 
     

    Hướng dẫn python json add key-value pair - python json thêm cặp khóa-giá trị


    Làm thế nào để bạn thêm một khóa

    txt ", 'r') dưới dạng f: data = json. Tải (f. read ()) #Data trở thành một từ điển #do mọi thứ với dữ liệu ở đây dữ liệu ['đã thêm_key'] = 'đã thêm_value' #và sau đó chỉ cần ghi dữ liệuQuay lại tệp với Mở ("Your_JSON_FILE.

    Làm cách nào để thêm khóa

    Có nhiều cách để thêm một cặp khóa/giá trị vào một đối tượng:..
    Sử dụng khung [] ký hiệu, ví dụ:obj ['name'] = 'john' ..
    Sử dụng dấu chấm.ký hiệu, ví dụ:obj.name = 'John' ..
    Sử dụng đối tượng.Phương thức gán (), chuyển nó một đối tượng mục tiêu và nguồn làm tham số ..

    Làm thế nào để bạn thêm một trường vào một JSON trong Python?

    Cách thêm một phần tử vào đối tượng JSON trong Python..
    Fruit_json = {"Apple": 1, "Orange": 2}.
    khóa = "chuối".
    Giá trị = 3 ..
    Fruit_json [khóa] = giá trị ..
    print(fruit_json).

    Làm cách nào để nhận chìa khóa

    Để có được một cặp giá trị khóa từ KiiObject, hãy gọi phương thức GET () của lớp KiiObject.Chỉ định khóa cho giá trị để nhận làm đối số của phương thức get ().Giá trị của khóa ở cấp độ đầu tiên của hệ thống phân cấp tài liệu JSON sẽ được lấy.call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method. The value of the key at the first level of the JSON document hierarchy will be obtained.