我被困在google colab中读取文件,它应该读取文件作为一个简单的JSON,但我甚至不能做一个json.dumps(file)
不会出现100 %的错误
上传文件:
import json
import csv
from google.colab import files
uploaded = files.upload()
打印工作,它显示文件的内容:
print(uploaded)
data = json.dumps(uploaded)
但我得到了Object of type 'bytes' is not JSON serializable
当尝试去做的时候json.dumps(uploaded)
文件不应该被读取为json
而不是bytes
什么?在其他一些情况下,我也将其测试为dictionary
JSON文件:
[
{
"type": "message",
"subtype": "channel_join",
"ts": "123",
"user": "DWADAWD",
"text": "<@DWADAWD> has joined the channel"
},
{
"type": "message",
"subtype": "channel_join",
"ts": "123",
"user": "DWADAWD",
"text": "<@DWADAWD> has joined the channel"
},
{
"text": "Let's chat",
"user_profile": {
"display_name": "XASD",
"team": "TDF31231",
"name": "XASD",
"is_restricted": false,
"is_ultra_restricted": false
},
"blocks": [
{
"type": "rich_text",
"block_id": "2N1",
"elements": [
{
"type": "rich_text_section",
"elements": [
{
"type": "text",
"text": "Let's chat"
}
]
}
]
}
]
}
]
发布于 2020-02-24 10:58:38
如果你只上传一个文件。你可以从它的values()
data = next(iter(uploaded.values()))
然后,您可以将json字符串转换为dict
d = json.loads(data.decode())
下面是一个例子notebook
发布于 2020-02-24 03:52:12
JSON处理Unicode字符串,而不是字节序列。尝试:
json.dumps(uploaded.decode("utf-8"))
发布于 2021-02-25 12:03:15
我更喜欢用io和文件..。
首先,我导入它们(和熊猫):
import io
import pandas as pd
from google.colab import files
然后,我使用文件小部件上传文件:
uploaded = files.upload()
要将数据加载到数据帧中,请执行以下操作:
df = pd.read_json(io.StringIO(uploaded.get('file.json').decode('utf-8')))
数据帧df包含所有json数据。
https://stackoverflow.com/questions/60366158
复制相似问题