【问题标题】:How to change values in a json file using JsonPath in python如何在python中使用JsonPath更改json文件中的值
【发布时间】:2019-02-18 17:57:42
【问题描述】:

我有以下 Json 文件:car_models.json

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

我有另一个 json 文件 data_change.json,其中包含有关 jsonpath 及其值的详细信息:

{
  "testcase_ID": "test_1A",
  "description": "Some description",
  "request_change_data": [
    {
      "element_path": "$.cars.[0].car_model",
      "element_value": "focus"
    }
  ]
}

我想读取 data_change.json 内容,使用此处的 element_path,解析 car_models.json 并将其值更新为 data_change.json 中的值。 如中,我想使用 jsonPath - $cars[0].car_model,通过 car_models.json 解析,并将 car_model 的值从 Mustang 更改为 focus。所以我更新后的 car_models.json 应该如下:

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

如何在 python 中做到这一点?

【问题讨论】:

    标签: python jsonpath


    【解决方案1】:

    猜测预期的答案需要有“焦点”而不是“福特”

    以下内容应为您提供:

    import json
    import re
    
    with open('cars_model.json') as f:
        cars_model = json.load(f)
    with open('data_change.json') as f:
        data_change = json.load(f)
    
    for elements in data_change['request_change_data']:
        element_path = elements['element_path']
        #Reg ex to get you the number (as a string) between the square brackets
        position_match = re.match(r"^.*\[(.*)\].*$", element_path)
        position = int(position_match.group(1))
        print position
        # Split on "period" to get the thing to match
        thing_to_change = element_path.split(".")[1]
        print thing_to_change
        value = elements['element_value']
        print value
        cars_model['cars'][0][thing_to_change] = value
    
    print cars_model
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      相关资源
      最近更新 更多