为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 AWS Athena 的多记录多行 JSON 转换为每记录单行 JSON?

如何将 AWS Athena 的多记录多行 JSON 转换为每记录单行 JSON?

BIG阳 2023-09-05 20:24:58
我想将 json 文件与 AWS Athena 结合使用,但 Athena 不支持多行 JSON。我有以下内容(其中一个值是 XML){  "id" : 10,  "name" : "bob",  "data" : "<some> \n <xml> \n <in here>"},{  "id" : 20,  "name" : "jane",  "data" : "<other> \n <xml> \n <in here>"}我需要雅典娜以下内容{ "id" : 10, "name" : "bob", "data" : "<some> <xml> <in here>" },{ "id" : 20, "name" : "jane", "data" : "<other> <xml> <in here>" }我正在使用 RazorSQL 从 DB2 导出数据,并尝试使用 Python 编写一些代码来“扁平化”它,但尚未成功。谢谢你!
查看完整描述

3 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

我最终做了一些快速而肮脏的事情


import json

with open('data.json') as jfile:

    data = json.load(jfile)

    for d in data:

        print(json.dumps(d) + ',')

哪个打印


{'id': 200, 'name': 'bob', 'data': '<other> \n <xml> \n <data>'},

{"id": 200, "name": "bob", "data": "<other> \n <xml> \n <data>"},

刚刚将输出保存到另一个文件:P


结果失败了,因为文件太大了,但是嘿..已经很接近了!


查看完整回答
反对 回复 2023-09-05
?
LEATH

TA贡献1936条经验 获得超6个赞

使用正则表达式


import re

html = '''

{

  "id" : 10,

  "name" : "bob",

  "data" : "<some> \n <xml> \n <in here>"

},

{

  "id" : 20,

  "name" : "jane",

  "data" : "<other> \n <xml> \n <in here>"

}

'''



def replaceReg(html, regex, new):

    return re.sub(re.compile(regex), new, html)


html = replaceReg(html,' \n ',' ')

html = replaceReg(html,'{[\s]+','{ ')

html = replaceReg(html,'[\s]+}',' }')

html = replaceReg(html,',[\s]+',', ')

html = replaceReg(html,'}, ','\n')

print (html)

结果:


{ "id" : 10, "name" : "bob", "data" : "<some> <xml> <in here>" 

{ "id" : 20, "name" : "jane", "data" : "<other> <xml> <in here>" }


查看完整回答
反对 回复 2023-09-05
?
HUH函数

TA贡献1836条经验 获得超4个赞

您只需要在写入另一个文件时替换结束换行符(\n ):


s=''

with open('input.txt','r') as f_in, open('output.txt', 'w') as f_out:

    for line in f_in:        

        s += line.replace('\n', '')

    f_out.write(s)

其中 input.txt 具有以下数据:


{

  "id" : 10,

  "name" : "bob",

  "data" : "<some> \n <xml> \n <in here>"

},

{

  "id" : 20,

  "name" : "jane",

  "data" : "<other> \n <xml> \n <in here>"

}


查看完整回答
反对 回复 2023-09-05
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信