Как добавить и обновить JSON файл - PullRequest
0 голосов
/ 20 февраля 2020

У меня ниже json формат файла, в зависимости от входных аргументов мне нужно добавить emp_email, если ключ совпадает, если нет совпадения, то добавить в конце.

    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  }
}

input_key = 'key2'

emp_email = 'cccc@email.com'

Над ключом 'cccc@email.com' необходимо обновить ключ key2 вместе с двумя существующими электронными письмами

input_key = 'key3'

emp_email = 'cccc@email.com'

Это должно добавить новую пару значений ключа в конце JSON

    {
  "key1": {
    "emp_email": [
      "xxxx@email.com",
      "yyyy@email.com"
    ]
  },
  "key2": {
    "emp_email": [
      "aaaaa@email.com",
      "bbbbb@email.com"
    ]
  },
  "key3": {
    "emp_email": [
      "ccccc@email.com"
    ]
  }
}

Я начал с кода ниже

try:
    json_file_read = open(json_file, "r")
    json_data = json.load(json_file_read)
except ValueError as e:
    print "Invalid JSON"
except IOError as e:
    print "File Not Present"


key_list = []
for key, value in json_data.items():
    key_list.append(key)
existing_key = " ".join(key_list)
existing_key_list = existing_key.split()
print(existing_key_list)

email_list = emp_email.split(",")
print email_list

for f in input_key.split(","):
    if f in existing_key_list:
        print "key exists...!!!"
        existing_email_list = json_data[f]["emp_email"]
        # create new appended list (new + existing)
        new_email_list = email_list + list(set(existing_email_list) - set(email_list))
        # not sure how to append for the specific key

    else:
        print "new key"
        # append the new key & email block at end

1 Ответ

0 голосов
/ 20 февраля 2020

Нет необходимости создавать список ключей. Вы можете просто использовать if f in json_data:, чтобы узнать, существует ли ключ.

for i, key in enumerate(input_key.split(",")):
    if key in json_data:
        print "key exists!"
        json_data[key]['emp_email'].append(email_list[i])
    else:
        print "new key"
        json_data[key] = {'emp_email': [email_list[i]]}
...