尝试缩进json转储然后写入文件

时间:2014-03-05 12:21:42

标签: python json

我有这个json转储没有很好的缩进,当我只是写入文件时不可读,所以为了使它更具可读性我做了这个

 with open(responseFile, 'w') as outfile:
      outfile.write(dumps(loads(content), indent=4))

但现在我得到了这个无效\ escape:错误。有什么建议 ?

e.g。含量:

{"devices":{"device":{"customAssetNumber":"","deviceName":"Shamik\'s iPhone","deviceOwner":"","deviceStatus":"Active","deviceType":"Smartphone","emailAddress":"sray@xyz.com","imeiEsn":342342,"installedDate":"2014-03-04T09:14:58","lastReported":"2014-03-05T06:48:42","DeviceID":"ApplC39GMAR7DTD8","Status":"Enrolled","mailboxDeviceId":"","mailboxLastReported":"","mailboxManaged":"","manufacturer":"Apple","model":"iPhone 4S","osName":"iOS 7","osServicePack":"","ownership":"Not Defined","platformName":"iOS","sourceID":1,"udid":"","unifiedTravelerDeviceId":"","username":"sray","wifiMacAddress":""},"count":1,"pageNumber":1,"pageSize":1}}

1 个答案:

答案 0 :(得分:5)

根据RFC-4627,只有"\和Unicode序列必须在字符串中进行转义。解决这个问题的一点点hackish方式是:

import re
re.sub(r'\\([^"u\\])', r'\1', content)

这应该有效,因为\不应该出现在有效JSON中的任何其他位置。