【问题标题】:JSON to pandas dict in python does not work [duplicate]python中的JSON到pandas dict不起作用[重复]
【发布时间】:2016-04-23 14:43:58
【问题描述】:

我在一个类中有一个函数 to_json,它将返回一个 JSON 字符串,如下所示:

{'clusters':[{ 'host':'hostj', 'name':'s3', 'port':'poorke', 'profile':'profil', 'region':'regieo', 'user':'userk' }]}

现在我想从中创建一个字典。当我使用以下代码时:

new_cluser_dict = json.loads(clusterx.to_JSON())

我收到以下错误:

Traceback (most recent call last):
  File "/Users/stevengerrits/anaconda/envs/myenv/lib/python3.4/site-packages/IPython/core/interactiveshell.py", line 3066, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-13-0887c8f07b97>", line 1, in <module>
    newdict = json.loads(clusterx.to_JSON())
  File "/Users/stevengerrits/anaconda/envs/myenv/lib/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/Users/stevengerrits/anaconda/envs/myenv/lib/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/stevengerrits/anaconda/envs/myenv/lib/python3.4/json/decoder.py", line 359, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

【问题讨论】:

  • 不要手动生成 json,而是使用 stdlib 中的 json 模块。 FWIW,在上面的示例中,您只是 根本不需要 json - 您需要的是一个 clusterx.to_dict() 方法,它返回一个普通的 python dict

标签: python json pandas


【解决方案1】:

需要把单引号换成双引号:

clusterx.to_JSON().replace("'", '"')

类似问题:python: single vs double quotes in JSON

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 2016-12-20
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多