简体   繁体   English

如何使用 python 从响应中获取键和值并将其存储在 json 文件中?

[英]How to fetch the key and values from response and store it in a json file using python?

I have a python code in this format that wants to fetch the key and values from response.我有一个这种格式的 python 代码,它想要从响应中获取键和值。

def test()
    data={u'Application': u'e2e', u'Cost center': u'qwerty', u'Environment': u'E2E', u'e2e3': u'aktest1', u'e2etest': u'aktest2', u'S68e2e': u'function',u'Application': u'test', u'Cost center': u'qwerty', u'Environment': u'E2E', u'e2e3': u'test7nov', u'e2etest': u'testapi', u'S68e2e': u'function'}

    new={}
    for k,v in data.items():
         new["key"] = k
         new["tags"] = []
    for d in v:
         flds = list(d)
         new["tags"].append({"key": k, "values": flds})
    print(new["tags"])
  with open(fileName, 'w') as f:
     json.dump(new["tags"], f, indent=3 * ' ')
test()

I am getting output as我得到 output 作为

 [ {'key': 'S68e2e', 'values': ['f']},
   {'key': 'S68e2e', 'values': ['u']}, 
   {'key': 'S68e2e', 'values': ['n']}, 
   {'key': 'S68e2e', 'values': ['c']}, 
   {'key': 'S68e2e', 'values': ['t']}, 
   {'key': 'S68e2e', 'values': ['i']}, 
   {'key': 'S68e2e', 'values': ['o']}, 
   {'key': 'S68e2e', 'values': ['n']}]

which is not correct.I expected to be这是不正确的。我希望是

[{'key': 'Application', 'values': 'e2e'}{'key': 'Cost center', 'values': 'qwerty'}{'key': 'e2etest', 'values': 'aktest2'}]

You can use a list comprehension to create a list of dictionaries that wrap your key,values in other key values您可以使用列表推导来创建一个字典列表,这些字典将您的键、值包装在其他键值中

[{ 'key': k, 'values': v } for k, v in data.items()]

暂无
暂无

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

相关问题 使用python从JSON响应中获取特定的键和值? - Take particular Key and values from JSON response using python? 如何从 Json 响应中获取值? - How to fetch the values from Json response? 如何从具有包含字典列表的字典的 python 中的 json 响应中获取值? - How to fetch values from json response in python having a dictionary containing list of dictionary? 如何使用 .json 文件将值添加到 python 中的键 - How to add values to a key in python using a .json file 如何从python中的json文件的特定键获取字段和值 - how to get fields and values from a specific key of json file in python 如何使用python one-line从bash中的json文件中获取嵌套键的值? - how to get values of a nested key from json file in bash using python one-liner? 有没有办法使用机器人框架仅将 json 响应中所需的键和值存储到文件中? - Is there a way to store only required keys and values from json response in to file using robot framework? 如何使用 Python 从 JSON 获取单个键的值列表 - How to get list of values of a single key from JSON using Python 如何从谷歌距离 API 的 json 响应中提取值并存储在 python Z6A8064B5DF4794555500553C47D - How to extract values from json response of Google's distance API and store in python dataframe? 如何从HTTP响应中提取JSON数据并将其存储在python中的excel /文本文件中 - How to scrap JSON data from HTTP response and store it in excel/text file with python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM