title: Unicode in Python - parsing JSON
body: <p>I've written this little code to take JSON files and import their contents into a consul key-value store - I was quite pleased that the recursion works exactly as I expect, however less pleased when the source .json files contained non-ASCII:</p>
  
  <pre><code>#!/usr/bin/python
  
  import sys
  import json
  
  filename = str(sys.argv[1])
  fh = open(filename)
  
  def printDict (d, path):
    for key in d:
      if isinstance(d[key], dict):
        printDict(d[key], path + str(key) + "/")
      else:
        print 'curl -X PUT http://localhost:8500/v1/kv/' + filename + path + key + ' -d "' + str(d[key]) + '"'
    return
  
  j = json.load(fh)
  printDict(j, "/")
  </code></pre>
  
  <p>A sample failing JSON file on disk:</p>
  
  <pre><code>{
      "FacetConfig" : {
          "facet:price-lf-p" : {
               "prefixParts" : "£"
          }
      }
  }
  </code></pre>
  
  <p>When I run the code as-is, I'm getting a nasty exception because that nice simple str() can't convert the UK currency pound sign to 7-bit ASCII:</p>
  
  <blockquote>
    <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128)</p>
  </blockquote>
  
  <p>How can I solve this without making too much of a dog's dinner of code that started out small and elegant? :)</p>