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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With