Python 将内容写入已经有头的json文件
因此,我正在试验happybase,我想用我已经放入的框架将扫描序列的内容写入json文档。这是预期输出文件的框架:Python 将内容写入已经有头的json文件,python,json,happybase,Python,Json,Happybase,因此,我正在试验happybase,我想用我已经放入的框架将扫描序列的内容写入json文档。这是预期输出文件的框架: [{ "Key": "", "Values": "" }] 从代码中,我希望实现预期json文件的最终格式: [{ "Key":"01/01/2009", "Values": { "actual:number":30000, "predicted:number":40000
[{
"Key": "",
"Values": ""
}]
从代码中,我希望实现预期json文件的最终格式:
[{
"Key":"01/01/2009",
"Values": {
"actual:number":30000,
"predicted:number":40000
}
},
{
"Key":"01/02/2009",
"Values": {
"actual:number":30000,
"predicted:number":40000
}
}]....
我的Hbase表的结构如下:
'01/01/2009','actual:number',value='30000'
'01/02/2009','predicted:number',value='40000'
这是我用来访问表的代码:
import happybase
import simplejson as sjson
import json
connection = happybase.Connection('localhost')
table = connection.table('Date-Of-Repairs')
file = open('test.json','wb+')
for key, data in table.scan(row_start='01/01/2009'):
a = key, data
print sjson.dumps(a)
json.dump(a,file, indent = 2)
file.close()
我想知道如何实现所需的json输出文件,以及如何停止写入json的内容打印出来,如下所示:
[
"01/01/2009",
{
"Actual:number": "10000",
"Predicted:number": "30000"
}
][
"01/02/2009",
{
"Actual:number": "40000",
"Predicted:number": "40000"
}
][
"01/03/2009",
{
"Actual:number": "50000",
"Predicted:number": "20000"
}
]
由于这是输出文件中显示的当前输出,Python库使用JSON文本的标准格式,因此它具有indent
参数,可帮助您控制应考虑缩进的空格数
json.dumps(pydict, indent=4)
如果您需要一个压缩的JSON,这很适合在生产中使用,您可以忽略它,python将生成缩小的文本,从而减少网络流量和解析时间
如果您想以自己的方式打印,那么您必须自己实现它,有一个名为“您可以将其作为如何实现的示例”的模块。谢谢@anand。我找到了答案。我只需要创建一个用于存储表数据的字典,然后将其附加到要存储在文件中的列表,从而生成一个完整的json文件 代码如下:
import happybase
import json
import csv
file = open('test.json','wb+')
store_file = {}
json_output = []
for key, data in table.scan(row_start='01/01/2009'):
store_file['Key'] = key
store_file['Value'] = data
json_output.append(store_file.copy())
print json_output
json.dump(json_output,file, indent = 2)
file.close()
这将产生:
[
{
"Key": "01/01/2009",
"value": {
"Actual:number": "10000",
"Predicted:number": "30000"
}
},
{
"Key": "01/02/2009",
"value": {
"Actual:number": "40000",
"Predicted:number": "40000"
}
},
{
"Key": "01/03/2009",
"value": {
"Actual:number": "50000",
"Predicted:number": "20000"
}
}
]
我希望这能帮助那些遇到这种问题的人