【问题标题】:How can I use jsonpath in python to change an element value in the json object如何在 python 中使用 jsonpath 来更改 json 对象中的元素值
【发布时间】:2019-02-15 09:44:19
【问题描述】:

我有以下 json 对象(比如 car_details.json):

{
   "name":"John",
   "age":30,
   "cars":
   [
     {
       "car_model": "Mustang",
       "car_brand": "Ford"
     },
     {
       "car_model": "cx-5",
       "car_brand": "Mazda"
     } 
}

我想通过 python 代码将 car_model 的值从 cx-5 更改为 cx-9。 我通过一个外部文件提供了这个元素的 json 路径。 json-path 表达式基本上表示为字符串。像这样的东西: '汽车[2].car_model' 并且新值也通过外部文件作为字符串提供: 'cx-9'

现在如何使用 jsonpath 表达式解析 car_details.json,并将其值更改为作为字符串提供的值,最后返回修改后的 json 对象

P.S 我想通过 python 代码做到这一点

【问题讨论】:

标签: python json jsonpath


【解决方案1】:

这是一种不使用 json 模块的方法。将数据加载到变量中。然后迭代汽车键/值。如果您找到您要查找的值的键,请将其设置为新值。

另外注意:你需要关闭你的数组块,否则你上面的 json 是无效的。通常我使用在线 json 解析器来检查我的数据是否有效等(将来可能会有所帮助)。

data =     {
       "name":"John",
       "age":30,
       "cars":
       [
         {
           "car_model": "Mustang",
           "car_brand": "Ford"
         },
         {
           "car_model": "cx-5",
           "car_brand": "Mazda"
         } 
       ]
    }

for cars in data['cars']:
    for key, value in cars.items():
        if key == "car_model" and value == "cx-5":
            cars[key] = "cx-9"
print(data)

如果你想从一个文件中加载你的 json 对象,我们假设它被称为“data.json”并且和你要运行的 python 脚本在同一个目录中:

import json

with open('data.json') as json_data:
    data = json.load(json_data)

for cars in data['cars']:
    for key, value in cars.items():
        if key == "car_model" and value == "cx-5":
            cars[key] = "cx-9"

print(data)

现在,如果您想将内容写入原始文件或新文件,在这种情况下,我正在写入一个名为“newdata.json”的文件:

import json
import re

with open('data.json') as json_data:
    data = json.load(json_data)
    print(data)

with open('external.txt') as f:
   content = f.read()
   print(content)

for cars in data['cars']:
    for key, value in cars.items():
        if key == "car_model" and value == "cx-5":
            cars[key] = content 

with open('newdata.json', 'w') as outfile:
    json.dump(data, outfile)

【讨论】:

  • 我想我应该更清楚。这是我的情况:我有一个文件“car_details.json”,它基本上是我想要解析元素并更新它们的 json 对象。我还有另一个文件:“request_change.json”,其中包含有关 jsonPaths 的详细信息car_details.json 中要更改的元素及其相应的值......“request_change.json”看起来像这样:{“testcase_ID”:“test_1A”,“description”:“Some description”,“request_change_data”:[ { "element_path": "[cars][0][car_model]", "element_value": "cx-9"}]} (续......)
  • Contd... 现在我必须阅读“request_change.json”,从那里获取 element_path 和 element_value(表示为字符串),使用这个 element_path 并解析 car_details.json并将其值更改为“element_value”的值
  • 您能否发布一个您将要读入的 request_change.json 文件的示例。
  • 看起来像这样: { "testcase_ID":"test_1A","description":"Some description","re​​quest_change_data": [ { "element_path": "[cars][0][car_model ]", "element_value": "cx-9" } ] } ...
猜你喜欢
  • 2019-02-18
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2020-03-22
相关资源
最近更新 更多