Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string file into json format file

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

the error is like this:

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

enter image description here

like image 470
arze ramade Avatar asked Jan 03 '14 10:01

arze ramade


People also ask

How do I convert a string to a JSON in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

Is a JSON file just a text file?

JSON files are lightweight, text-based, human-readable, and can be edited using a text editor. The JSON format was originally based on a subset of JavaScript but is considered a language-independent format, being supported by many different programming APIs. JSON is commonly used in Ajax Web application programming.

Is JSON a string file?

JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two.


1 Answers

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)

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

like image 104
Shaung Avatar answered Sep 21 '22 13:09

Shaung