从JSON输出

时间:2018-04-17 11:05:10

标签: python json python-requests

我使用requests获取REST API调用的输出,将输出保存到1.json,然后从该json文件提取描述和JIRA键

import csv
import urllib2
import argparse
import json
from bson import json_util

#password = str(sys.argv[1])
headers = {
    'Content-Type': 'application/json',
}
params = (
    ('jql', 'project="Technology" AND summary~"workspace creation*" AND issuetype="Task" AND status!="DONE"'),
)
response = requests.get('https://jira.company.com/rest/api/2/search', headers=headers, params=params, auth=('user', 'Pass'))

with open('1.json', 'w') as outfile:
  outfile.write(response.content)
if sys.version[0] == '2':
    reload(sys)
    sys.setdefaultencoding("utf-8")
sys.stdout = open('output.txt','wt')

datapath = '1.json'




data = json.load(open(datapath))
for issue in data['issues']:
  if len(issue['fields']['subtasks']) == 0 and 'description' in issue['fields']:
   custom_field = issue['fields']['description']
   print custom_field
   print issue['key']

Output.txt的:

  User:someuser^M
    ^M
    First Name:some^M
    ^M
    Last Name:user
    TECH-1427

我需要以下列格式从此output.txt获取csv文件:

someuser,some,user,TECH-1427

我正在使用此代码

re.findall(r'\bUser:(\S+)\s+First Name:(\S+)\s+Last Name:(\S+)\s+(TECH-\d+)', data)

data是output.txt文件的内容

现在,这只有在我从output.txt中手动删除^M时才有效,所以如何在解析1.JSON文件时删除^M,以便从output.txt中删除它?

尝试替换但结果相同

sys.stdout = open('out.txt','wt')


    with open ("output.txt", "r") as myfile:
      data=myfile.read()


    print data.replace('^M','')

1 个答案:

答案 0 :(得分:1)

尝试更换如下:

somestring.replace('\r','')

其中somestring包含您下载的数据字符串数据