Winter
Winter

Reputation: 1741

How do I encode a global Python variable with JSON?

I'm trying to figure out how I can encode my globals into a JSON format, I'm not even sure if it's possible. I'm using Python 2.7.8, and I've tried this from a few different approaches:

# Variables
value = "String" # String
value2 = 0 # Integer
value3 = True # Boolean

json.dumps({"key": value, "key2": value2, "key3": value3}, sort_keys=True, indent=4, separators=(',', ': '))

I also tried making it a string first (with and without the curly braces, with/without quotations on the string value etc.)

json_raw = '{"key": %s, "key2": %d, "key3": %s}' % (value, value2, value3)
json.dumps(json_raw, sort_keys=True, indent=4, separators=(',', ': '))

However, with each one of these attempts I get the error:

AttributeError: 'str' object has no attribute 'dumps'

Any ideas?

Upvotes: 2

Views: 7198

Answers (2)

mobiusklein
mobiusklein

Reputation: 1423

This is definitely doable. Reading your code, you're using the json.dump function. dump expects the second argument to be a file-like object. The dumps function, note the s, does not, and returns the JSON representation of the data as a string.

Upvotes: 0

Aida Paul
Aida Paul

Reputation: 2722

Let me answer with code:

value = "String" # String
value2 = 0 # Integer
value3 = True # Boolean
json_map = {}
json_map["Some string"] = value
json_map["Some int"] = value2
json_map["Some bool"] = value3
result = json.dumps(json_map)

And then the result containts '{"Some int": 0, "Some string": "String", "Some bool": true}'. All thanks to the magic of python dictionaries and json.dumps.

Upvotes: 5

Related Questions