2

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?

2 Answers 2

6

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.

1
  • Awesome, I got it working with your solution. Thanks!
    – Winter
    Commented Nov 8, 2014 at 4:59
0

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.

1
  • Thanks for the answer! Sorry my code does have json.dumps but I accidentally put json.dump in my question. This is helpful though, I'll keep it in mind for future reference.
    – Winter
    Commented Nov 8, 2014 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.