从json响应[Python]复制数据

2024-10-01 00:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个场景,我试图从从GET请求获得的json响应中提取数据,然后通过更改一些值来重建json数据,然后在重建json数据后同时发送PUT请求(即,在更改idter值之后) 下面是目标json响应

target_json = {
  "name": "toggapp",
  "ts": [
    1234,
    3456
  ],
  "gs": [
    {
      "id": 4491,
      "con": "mno"
    },
    {
      "id": 4494,
      "con": "hkl"
    }
  ],
  "idter": 500,
  "datapart": false
}

从上面的json中,我试图将idter值更改为我的自定义值,并再次将其重建为json数据,然后发布新的json数据。 以下是我尝试过的:

headers = {'Authorization': 'bearer ' + auth_token, 'Content-Type':'application/json', 'Accept':'application/json'}
tesstid =[7865, 7536, 7789]
requiredbdy = []
for key in testid:
    get_metadata_targetjson= requests.get('https://myapp.com/%s' %key, headers = headers)
    metadata=get_metadata_target.json()
    for key1 in metadata:
        requiredbdy.append(
                {
                        "metadata" : [{
                        "name": key1['name'],
                        "ts": key1['ts'],
                      "gs": key1[gs],
                      "idter": 100,  #custom value which I want to change
                     "datapart": false
                     } ]
                    }
                  )
        send_metadata_newjson= requests.put('https://myapp.com/%s' %key, headers = headers data = requiredbdy)
        print(send_metadata_newjson.status_code)

这种方法好吗?或者我如何继续以实现此场景


Tags: 数据keynamegsidjsontargetget
2条回答

有一个小脚本,它用来在一些非常长且令人不安的JSON中查找条目。不是很漂亮,文件也不完整,但可能对您的场景有所帮助

from RecursiveSearch import Retriever

def alter_data(json_data, key, original, newval):
    '''
    Alter *all* values of said keys
    '''
    retr = Retriever(json_data)
    for item_no, item in enumerate(retr.__track__(key)): # i.e. all 'value'
        # Pick parent objects with a last element False in the __track__() result,
        # indicating that `key` is either a dict key or a set element
        if not item[-1]: 
            parent = retr.get_parent(key, item_no)
            try:
                if parent[key] == original:
                    parent[key] = newval
            except TypeError:
                # It's a set, this is not the key you're looking for
                pass

if __name__ == '__main__':
    alter_data(notification, key='value', 
               original = '********** THIS SHOULD BE UPDATED **********',
               newval = '*UPDATED*')

您可以使用内置的^{}模块进行类似的操作

import json

my_json = """
{
  "name": "toggapp",
  "ts": [
    1234,
    3456
  ],
  "gs": [
    {
      "id": 4491,
      "con": "mno"
    },
    {
      "id": 4494,
      "con": "hkl"
    }
  ],
  "idter": 500,
  "datapart": false
}
"""

json_obj = json.loads(my_json)
json_obj['idter'] = 600
print(json.dumps(json_obj))

印刷品

{"name": "toggapp", "ts": [1234, 3456], "gs": [{"id": 4491, "con": "mno"}, {"id": 4494, "con": "hkl"}], "idter": 600, "datapart": false}

相关问题 更多 >