将内容写入已经具有标头的json文件



所以我正在试验happybase,我想用我已经放入的骨架将扫描序列的内容写入json文档。这是预期输出文件的骨架:

[{
   "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库使用json文本的标准格式,它有indent参数,可以帮助您控制缩进时应考虑的空格数。

json.dumps(pydict, indent=4)

如果你需要一个压缩的JSON,它很适合在生产中使用,你可以简单地忽略它,python会生成缩小的文本,从而减少网络流量和解析时间。

如果你想要你的打印方式,那么你必须自己实现它,有一个名为pjson的模块,你可以把它作为如何实现它的例子。

谢谢@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"
   }
 }
]

我希望这能帮助任何遇到这样问题的人。

最新更新