【问题标题】:Why is my json.loads() call improperly formatting strings?为什么我的 json.loads() 调用不正确地格式化字符串?
【发布时间】:2019-08-06 20:00:02
【问题描述】:

我正在为 Cortex/Hive 构建一个自定义响应程序,但我无法让我的请求响应正确转换为 JSON 格式。在本地开发环境中测试时,我在 getCount 函数中的代码可以完美运行,但是当向其中添加 cortex 响应器包装器时,我的代码会失败。

由于响应程序从 Cortex 运行,我没有收到超出“输入:null”的错误消息,因此我不得不写入错误日志。使用此日志,我确定错误源于data = json.loads(response.text) 行。我尝试使用简单的 json,从 response.text 中对所需值进行正则表达式,更改编码方法,并因为它无法正常工作而将我的头撞在键盘上。

代码:

import requests

import json

from cortexutils.responder import Responder

class Search(Responder):
        def __init__(self):
                # Debug
                with open('/xxx/xxx/xxx/xxx/error.log','a') as error_log:
                        error_log.write('Starting: \n')
                        error_log.write('\n\n')
                # End Debug

                Responder.__init__(self)
                self.apiuser = self.get_param('config.api_user', None)
                self.apikey = self.get_param('config.api_key', None)
                self.url = self.get_param('config.api_url', None)
                self.ioc_type = self.get_param('data.dataType', None)
                self.ioc = self.get_param('data.data', None)
                # Debug
                with open('/xxx/xxx/xxx/xxx/error.log','a') as error_log:
                        error_log.write('User ID: \n')
                        error_log.write(self.apiuser)
                        error_log.write('\n\nSecret: \n')
                        error_log.write(self.apikey)
                        error_log.write('\n\n')
                        error_log.write('IOC Type: \n')
                        error_log.write(self.ioc_type)
                        error_log.write('\n\n')
                        error_log.write('Value: \n')
                        error_log.write(self.ioc)
                        error_log.write('\n\n')
                # End Debug

        def getCount(self):
                with open('/xxx/xxx/xxx/xxx/error.log','a') as error_log:
                        error_log.write('Starting Count: \n')
                        error_log.write('\n\n')

                url = self.url

                headers={'Content-Type': 'application/json'}

                params={'type': self.ioc_type, 'value': self.ioc}

                response = requests.request("GET", url, headers=headers, params = params, auth=(self.apiuser, self.apikey))

                data = json.loads(response.text)
                with open('/xxx/xxx/xxx/xxx/error.log','a') as error_log:
                        error_log.write('Response: ')
                        error_log.write(data)

                deviceCount = data['resources'][0]['device_count']

                self.count = deviceCount



        def run(self):
                Responder.run(self)

                self.getCount()

                self.operations()

        def operations(self):
                return [self.build_operation('AddTagToCase', tag= self.count)]

if __name__ == '__main__':
        Search().run()


Results from response.text:
 {"meta":{"query_time":0.014920091,"trace_id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"},
"resources":[{"id":"sha256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"type":"sha256",
"value":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"device_count":11}],"errors":[]}

Error Logging results:

Starting:


User ID:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Secret:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

IOC Type:
sha256

Value:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

run starting:
Starting Count:

self.count 应该等于 device_count,但 json.loads 无法格式化此响应。这可以在我的错误日志结果中看到,其中 Count() 开始但在数据写入之前突然结束。

如果您可以提供有关为什么无法正确格式化响应的原因,请提供一些说明。

谢谢

【问题讨论】:

  • 请提取minimal reproducible example。作为新用户,也请访问tourHow to Ask
  • 您能否编辑问题以包含示例response.text 值?
  • “空输入”和“空变量”在 Python 中没有任何特殊意义。能详细点吗?
  • @UlrichEckhardt 我包含了一个经过清理的示例响应
  • @JohnGordon 我包含了一个经过清理的示例响应

标签: python json python-requests


【解决方案1】:

这是我使用 requests 模块从 API 获取 json 响应的标准方式

response = requests.get(url, headers=headers, params=params, auth=(self.apiuser, self.apikey)).json()

【讨论】:

  • 我试过那个方法没有成功。我提供了一个示例响应,可能能够更深入地了解该问题
  • 能否在json.loads()语句中记录response.status_code、response.encoding、response.text和catch异常的结果?
猜你喜欢
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 2017-09-25
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多