0

所以我正在试验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"
   }
]

因为这是输出文件中显示的当前输出

4

2 回答 2

0

Python json库对 JSON 文本使用标准格式,它具有indent参数,可以帮助您控制应考虑缩进的空格数。

json.dumps(pydict, indent=4)

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

如果您想要以自己的方式打印,那么您将不得不自己实现它,有一个名为pjson的模块,您可以将其作为如何执行此操作的示例。

于 2016-01-11T07:40:22.110 回答
0

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

我希望这可以帮助任何遇到此类问题的人。

于 2016-01-12T05:05:25.550 回答