将字符串文件转换为json格式文件 [英] Converting string file into json format file

查看:54
本文介绍了将字符串文件转换为json格式文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,假设我有一个名为 "string.txt" 的字符串文本文件,我想将其转换为 json 文本文件.我想做什么?我曾尝试使用 'json.loads()' ,但它从不适合我!这是我的文本文件的一部分:

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 :

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()

错误是这样的:

obj, end = self.raw_decode(s, idx=_w(s, 0).end())类型错误:预期的字符串或缓冲区

obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer

推荐答案

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)

参见 http://docs.python.org/2/library/json.html#basic-usage

这篇关于将字符串文件转换为json格式文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆