Python 将字符串文件转换为json格式文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20901018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string file into json format file
提问by arze ramade
Ok , let say that I have a string text file named "string.txt" , and I want to convert it into a json text file. What I suppose to do? I have tried to use 'json.loads()' ,but it never works with me! here is a part from my text file :
好的,假设我有一个名为 "string.txt" 的字符串文本文件,我想将其转换为 json 文本文件。我想做什么?我曾尝试使用 'json.loads()' ,但它从不适合我!这是我的文本文件的一部分:
rdian","id":"161428670566653"},{"category":"Retail and consumer merchandise","category_list":[{"id":"187937741228885","name":"Electronics Store"},{"id":"191969860827280","name":"Photographic Services & Equipment"}
any help please? edit: I have use this code:
有什么帮助吗?编辑:我使用了这个代码:
import json
f = open("string.txt", 'w')
f1 = open("stringJson.txt", 'r')
f.write(json.dumps(json.loads(f), indent=1))
f.close()
the error is like this:
错误是这样的:
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: 预期的字符串或缓冲区


采纳答案by Shaung
import json
with open("string.txt", "rb") as fin:
content = json.load(fin)
with open("stringJson.txt", "wb") as fout:
json.dump(content, fout, indent=1)
回答by IgnacioUy99
In this case
You need to read the content of file
在这种情况下,
您需要读取文件的内容
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
import json
f = open("string.txt", 'w')
f1 = open("stringJson.txt", 'r')
data = json.loads(f1)
f.write(json.dumps(data, indent=1))
f.close()

