简体   繁体   English

从 json 响应复制数据 [Python]

[英]copying data from json response [Python]

I have a scenario where I am trying to extract data from json response which is obtained from the GET request and then rebuilding the json data by changing some values and then sending a PUT request at same time after rebuilding the json data(ie, after changing idter value) below is the target json response.我有一个场景,我试图从 json 响应中提取数据,该响应是从 GET 请求获得的,然后通过更改一些值重建 json 数据,然后在重建 Z466DEEC76ECDF5FCA6D38571F632 数据后同时发送 PUT 请求(在更改后下面的idter值)是目标 json 响应。

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

from the above json I am trying to change the idter value to my custom value and rebuild it into json data again and post the new json data.从上面的 json 我正在尝试将idter值更改为我的自定义值并再次将其重建为 json 数据并发布新的 json 数据。 Here is what I have tried:这是我尝试过的:

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)

Is this approach fine or How do I proceed in order to achieve this scenario.这种方法是否可行,或者我该如何进行才能实现这种情况。

You can use the built-in json module for this like so您可以像这样使用内置的json模块

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))

Prints印刷

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

There's this small script used it to find entries in some very long and unnerving JSONs.有这个小脚本用它来查找一些非常长且令人不安的 JSON 中的条目。 not very beautifull und badly documented but maybe helps in your scenario.不是很漂亮,记录也不是很好,但可能对您的情况有所帮助。

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*')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM