How do I take a python dictionary where the keys and values are Strings and convert it into a JSON String.
This is what I have right now:
import json def create_simple_meeting(subject, startDate, endDate, location, body): info = dict() if(subject != ""): info["subject"] = subject if(startDate != ""): info["startDate"] = startDate if(endDate != ""): info["endDate"] = endDate if(body != ""): info["body"] = body if(location != ""): info["location"] = location print(json.dumps(dict)) create_simple_meeting("This is the subject of our meeting.","2014-05-29 11:00:00","2014-05-29 12:00:00", "Boca Raton", "We should definitely meet up, man")
And it gives me this error
File "/Users/bens/Documents/workspace/Copy of ws1 for py java playing/opias/robot/libs/playing.py", line 15, in create_simple_meeting print(json.dumps(dict)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <type 'dict'> is not JSON serializable
In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
Method 2: Writing JSON to a file in Python using json.dump() Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.
You are trying to serialise the type object, dict
, instead of info
. Dump the right variable:
print(json.dumps(info))
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