I'm using python 3.x. I have a python dictionary
my_dict={'key1':'A12b','Key2':'cd12'}
I want to convert it in JSON format. I need it in this format
my_dict1={"key1":"A12b","Key2":"cd12"}
I tried my_dict1=json.dumps(my_dict) & I'm getting '{"key1": "A12b", "Key2": "cd12"}' which is of type string. Can you suggest me how do I convert?
That is as close to JSON as you can get in Python. Send that object to a webserver and it will be interpreted as JSON which is probably what you want.
dict in python is a kind of data structure, while json is a kind of data format;
I suppose you want to convert a dict into a json-formated file? Then you should use json.dump(obj, fp) instead of json.dumps(obj). The first one dumps a python dict obj to a file fp, and the second function make obj into a json formatted string.
In your case, to dump a dict obj into a file example.json, code it like below:
import json
my_dict={'key1':'A12b','Key2':'cd12'}
with open('example.json', 'w') as file:
json.dump(my_dict, file)
Good luck!
Related
I have a little question! How can I add an object or string to an already existing JSON file in Python?
At the moment I have written that snip of code. But is it going to always add a new JSON file. I hope you know my problem. :D
json.dump(txtdictionary_main,open('filename-manager.json','w'),indent=4,sort_keys=True)
Convert file to dictionary:
with open('filename-manager.json') as json_file:
txtdictionary_main = json.load(json_file)
Add values to dictionary:
txtdictionary_main[key] = value
Convert dictionary back to JSON:
json_object = json.dumps(txtdictionary_main , indent = 4)
I am using Python to convert data from a xml file to json and putting it in a file. I am using xmltodict to convert to dictionary using 'parse' and then converting into json using 'dumps'. Here is the code below: -
import xmltodict
import json
with open('note.xml') as xml_file:
my_dict=xmltodict.parse(xml_file.read())
xml_file.close()
json_data=json.dumps(my_dict)
with open('note.json', 'w') as f:
json.dump(json_data, f)
Here is a sample xml file that I have used. However, in the output, I am getting something not quite json like, with the added backslash. Looks like gibberish: -
"{\"note\": {\"to\": \"Tove\", \"from\": \"Jani\", \"heading\": \"Reminder\", \"body\": \"Don't forget me this weekend!\"}}"
I am trying to understand why I am not able to get data in proper json form. Is there anything wrong with my code? Please note that I am not a very skilled programmer and have only used Python sporadically.
You need to add below code after json_data=json.dumps(my_dict) to convert string to json object
json_data = json.loads(json_data)
I'm trying to parse this json file that I recieved from an API call.
"[{\"ip\":\"xx.xx.xxx.xx\",\"dns\":\"xxx.net\",\"netbios\":\"xxxxx\",....
I dumped it to a file like so:
with open('jayo.json', 'w') as j:
json.dump(r.text, j) #r.text being the API response
json should just be a straightforward dictionary, right? why does mine have all the back-slashes?
How would I print each value on it's own? IP/DNS etc.
You are receiving the API response as a str you need to load it using json before dumping it. json.dump is usually used with collections not strings as it does the conversion for you.
data = json.loads(r.text)
with open('jayo.json', 'w') as j:
json.dump(data, j)
If you need the data in the file before overwriting it load it use
with open('jayo.json', 'r') as j:
data = json.load(j)
Are you trying to load the JSON in Python, or dump it to a file? (or both?)
json.dump is for writing a Python object to a JSON file. r.text is just a string, so the resulting format will look like a single string in JSON (including all of the escaped quotes) instead of a full object.
Presumably you want to use json.loads to load the JSON string into a Python object before using json.dump. Or if you want to dump the JSON string straight to a file, you can just use j.write(r.text).
I'm trying to manipulate a JSON file and dump it back out.
Below is the JSON file - Note how there are two dictionaries wrapped together below...:
{"installed":
{"client_id":"xxx",
"project_id":"quickstart-1557411376659",
"auth_uri":"xxx",
"token_uri":"xxx",
"auth_provider_x509_cert_url":"xxx",
"client_secret":"xxx",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]
}
}
I'm trying to use the following python code to read in the JSON file manipulate it, and write it back out.
with open('google_sheets_credentials.json', 'r+') as file:
google_sheets_auth_dict = json.load(file)
#Manipulate file contents here
with open('google_sheets_credentials.json', 'r+') as file:
json.dump(google_sheets_auth_dict, file)
This code fails after a couple of runs because multiple dictionaries need to be wrapped in a list to be written out as JSON - like so:
The reasoning behind this requirement is explained here
with open('google_sheets_credentials.json', 'r+') as file:
json.dump([google_sheets_auth_dict], file)
The problem is that I can't do that in this case because this JSON is ultimately being fed into google sheets' API where it does not expect the JSON to be wrapped in a list.
How might I read this file in, manipulate, and spit it back out in the format expected by google?
This example case:
import json
example_json = '''{"installed":
{"client_id":"xxx",
"project_id":"quickstart-1557411376659",
"auth_uri":"xxx",
"token_uri":"xxx",
"auth_provider_x509_cert_url":"xxx",
"client_secret":"xxx",
"redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]
}
}'''
google_sheets_auth_dict = json.loads(example_json)
google_sheets_auth_dict['client_id'] = 'yyy'
print(json.dumps(google_sheets_auth_dict))
seems to work fine
I'm guessing that something is going wrong in the #Manipulate file contents here bit, which is not shown. Or, the example JSON does not look like the failure case.
I have a file containing in each row a JSON object, which means that the whole file is not a valid JSON, but only each row by itself is.
What I'm trying to do is to iterate through the file and convert each row into a JSON and then print the values, simple because only each row by itself is a valid JSON.
The file looks like this:
{json object 1}
{json object 2}
{json object 3}
{json object 4}
each JSON object looks like this:
{"event":"Session","properties":{"time":1423353612,"duration":33}}
The code I'm trying to run with no success is the following:
import simplejson as json
with open("sessions.json", "r") as f:
for line in f:
j=json.JSONEncoder().encode(line)
print j['event']['time']
print j['event']['duration']
I'm getting the following error:
TypeError: string indices must be integers, not str
Any ideas why?
Thanks!
You're calling the wrong thing. Converting from a JSON string to a Python object is decoding, not encoding. And in any case, it's better to use the top-level functions in the json module, rather than the underlying classes themselves.
for line in f:
j = json.loads(line)
Edit
Given the structure you show, j['event'] is the string "Session" and it does not have a sub-property time. Looks like you mean j['properties']['time'].