如何更改json文件的某些值?

sg24os4d  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(397)

我有一个json文件,它是dic的列表。例如,它的两个要素是:

  1. [{'key': 'chief information security officer',
  2. 'top_transitions': [{'security architect': 5.0},
  3. {'cyber security manager': 3.0},
  4. {'information security officer': 3.0}]},
  5. {'key': 'security auditor',
  6. 'top_transitions': [{'information security analyst': 9.0},
  7. {'information security officer': 9.0},
  8. {'it auditor': 6.0}]}]

我需要改变 top_transitions 以我的手为例,我可以怎样改变 {'security architect': 5.0}{'student': 15.0} ?

qxgroojn

qxgroojn1#

你可以用这个例子来改变 {"security architect": 5.0}{"student": 15.0} ( data 从json文件加载):

  1. import json
  2. to_search = {"security architect": 5.0}
  3. to_replace = {"student": 15.0}
  4. for item in data:
  5. if to_search in item["top_transitions"]:
  6. item["top_transitions"].remove(to_search)
  7. item["top_transitions"].append(to_replace)
  8. print(json.dumps(data, indent=4))

印刷品:

  1. [
  2. {
  3. "key": "chief information security officer",
  4. "top_transitions": [
  5. {
  6. "cyber security manager": 3.0
  7. },
  8. {
  9. "information security officer": 3.0
  10. },
  11. {
  12. "student": 15.0
  13. }
  14. ]
  15. },
  16. {
  17. "key": "security auditor",
  18. "top_transitions": [
  19. {
  20. "information security analyst": 9.0
  21. },
  22. {
  23. "information security officer": 9.0
  24. },
  25. {
  26. "it auditor": 6.0
  27. }
  28. ]
  29. }
  30. ]
展开查看全部

相关问题