【问题标题】:python json match multiple and replacepython json匹配多个并替换
【发布时间】:2016-05-16 14:01:01
【问题描述】:

在寻找解决方案时需要您的帮助。我有以下 json

[{"source":"AA","target":"BB","metric":"10","local_interface":"100","re​​mote_interface":"200"}, {"source":"AA","target":"BB","metric":"10","local_interface":"111","re​​mote_interface":"222"}, {"source":"BB","target":"AA","metric":"10","local_interface":"200","re​​mote_interface":"100"}]

目标是:

  • 获取第一个元素(即:模式)作为源/目标/本地接口
  • 在剩余元素中搜索与 source=pattern.target 、 target=pattern.source 、remote_interface=pattern.local_interface 匹配的元素
  • 从 json 中移除元素。

希望这是有道理的。

【问题讨论】:

  • 那么你的代码在哪里,它到底有什么问题?

标签: python json


【解决方案1】:

你追求这么简单的事情吗?

j = [{"source":"AA","target":"BB","metric":"10",
 "local_interface":"100","remote_interface":"200"},
 {"source":"AA","target":"BB","metric":"10",
 "local_interface":"111","remote_interface":"222"},
 {"source":"BB","target":"AA","metric":"10",
 "local_interface":"200","remote_interface":"100"}]

s = j[0]["source"]
print(s)
t = j[0]["target"]
print(t)
li = j[0]["local_interface"]
print(li)

print('Find source ==', t)
for i in range(1,3):
  if j[i]['source'] == t:
    print("Is match:", j[i])

print()

del(j[1])
print("after deletion:", j)

【讨论】:

  • 感谢乔根。我需要检查所有三个值。我猜如果 j[i]['source'] == t 和 j[i]['target'] == s 和 j[i]['remote_interface'] == li: 会起作用
  • 当然可以。而要删除的数组元素是i中的索引
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 2016-11-30
相关资源
最近更新 更多