目前,我正在将数据库从 firebase 导出到 JSON,但它以数组的形式出现。
[{"ConnectionTime": 19.23262298107147, "objectId": "01331oxpVT", "FirmwareRevision": "201504270003 Img-B", "DeviceID": "EDF02C74-6518-489E-8751-25C58F8C830D", "PeripheralType": 4, "updatedAt": "2015-10-09T04:01:39.569Z", "Model": "Bean", "HardwareRevision": "E", "Serial": "Serial Number", "createdAt": "2015-10-09T04:01:39.569Z", "Manufacturer": "Punch Through Design"}, {"ConnectionTime": 0.3193170428276062, "objectId": "018Mv1g6I8", "DeviceID": "42635033-DF3A-4109-A633-C3AB829BE114", "PeripheralType": 2, "updatedAt": "2015-12-08T04:20:41.950Z", "createdAt": "2015-12-08T04:20:41.950Z"}]
然后我收到此错误 - 遇到数组开头但没有对象开头。'}]
如何将其更改为不是数组而只是数据列表。我还需要在每组数据之间有一个换行符,但我假设一旦我从数组中获取数据,我当前拥有的代码就会执行此操作。我的代码如下。感谢您的帮助!
firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/connection_info_parse', None)
# id_keys = map(str, result.keys()) #filter out ID names
with open("firetobqrestore1.json", "w") as outfile:
# for id in id_keys:
json.dump(result, outfile, indent=None)
outfile.write("\n")
最佳答案
听起来您的工作流程中的某些内容需要换行符分隔的 JSON,尽管您尚未明确说明导致此错误的原因。
有了这个警告,我认为这就是您正在寻找的:
import json
with open("firetobqrestore1.json", "w") as outfile:
for line in result:
json.dump(line, outfile, indent=None)
outfile.write("\n")
这会将单独的 json 对象写入每一行。
这还假设 result
是一个实际的 Python 对象而不是 JSON 字符串。如果它是一个字符串,您需要首先使用以下内容解析它:
result = json.loads(result)
关于Python-如何从数组中复制所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45364918/