【问题标题】:how to remove a back slash from a JSON file如何从 JSON 文件中删除反斜杠
【发布时间】:2019-02-02 15:05:59
【问题描述】:

我想创建一个这样的 json 文件:

{"946705035":4,"946706692":4 ...}

我正在获取一个仅包含 Unix Timestamp 的列并将它们分组。

result = data['Last_Modified_Date_unixtimestamp_no_time'].value_counts()

In [21]: result.head()
Out[21]: 
1508284800    131
1508716800    106
1508371200    101
1508457600     99
1508630400     96
Name: Last_Modified_Date_unixtimestamp_no_time, dtype: int64

转换成字典

result = result.to_dict()
result
'''
{1507161600: 1,
 1507852800: 1,
 1508198400: 64,
 1508284800: 131,
 ...
 1535155200: 1,
 1535241600: 1}
'''

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.dump(result, fp, indent=4)

结果 这是我期望的数据结构

{"946705035":4,"946706692":4}

【问题讨论】:

标签: python json python-3.x


【解决方案1】:
data_json=df.to_json(orient='records')
parsed=json.loads(data_json)

with open('my_data.json', 'w') as f:
    json.dump(parsed, f, indent=4)

【讨论】:

  • 请添加一些关于如何解决问题的解释
【解决方案2】:

解决上述问题最简单的方法是玩json.dumps()和json.loads()。

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.loads(result, fp)

【讨论】:

  • 是的。你可以试试。
  • json.loads() 的第二个参数没有意义 - 它只接受一个位置参数。
【解决方案3】:

您将 JSON 转储两次,这会导致在第二次转储时转义引号。 (在第一个json.dumps 之后,结果只是一个字符串,所以你只是再次转储一个字符串而不是一个字典)

import json
# result = json.dumps(result)

with open('result.json', 'w') as fp:
    json.dump(result, fp, indent=4)

或者删除第二个转储:

import json
result = json.dumps(result)

with open('result.json', 'w') as fp:
    # json.dump(result, fp, indent=4)
    print(result, file=fp)

【讨论】:

  • result的类型有简单的测试吗?这样,可以写if type(result) is <json string>: fp.write(result) ... else: json.dump(result,fp)
  • @blong type(result) is str,但更好的是,跟踪您的代码并注意 在哪里 JSON 被转储。如我的回答所述,只做一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 2016-12-05
相关资源
最近更新 更多