Converting a raw list to JSON data with Python
<p>I have a raw list <code>sorteddict</code> in the form of :</p>

<pre><code>["with", 1]
["witches", 1]
["witchcraft", 3]
</code></pre>

<p>and I want to generate more legible data by making it a JSON object that looks like:</p>

<pre><code>"Frequencies": {
    "with": 1,
    "witches": 1,
    "witchcraft": 3,
    "will": 2
}
</code></pre>

<p>Unfortunately so far, I have only found a manual way to create data as shown above, and was wondering if there was a much more eloquent way of generating the data rather than my messy script. I got to the point where I needed to retrieve the last item in the list and ensure that there was no comma on the last line before I thought I should seek some advice. Here's what I had:</p>

<pre><code>comma_count = 0
for i in sorteddict:
    comma_count += 1

with open("frequency.json", 'w') as f:
    json_head = "\"Frequencies\": {\n"
    f.write(json_head)
    while comma_count &gt; 0:
        for s in sorteddict:
            f.write('\t\"' + s[0] + '\"' + ":" + str(s[1]) + ",\n")
            comma_count -= 1
    f.write("}")
</code></pre>

<p>I have used <code>json.JSONEncode.encode()</code> which I thought that was what I was looking for, but what ended up happening is <code>"Frequencies"</code> would be prepended to each <code>s[0]</code> item. Any ideas to clean the code?</p>

<p>You need to make a nested dict out of your current one, and use <code>json.dumps</code>. Not sure how sorteddict works, but: </p>

<pre><code>json.dumps({"Frequencies": mySortedDict})
</code></pre>

<p>should work. </p>

<p>Additionally, you say that you want something json encoded, but your example is not valid json. So I will assume that you actually want legitimate json.</p>

<p>Here's some example code: </p>

<pre><code>In [4]: import json

In [5]: # No idea what a sorteddict is, we assume it has the same interface as a normal dict. 

In [6]: the_dict = dict([
   ...:     ["with", 1],
   ...:     ["witches", 1],
   ...:     ["witchcraft", 3],
   ...: ])

In [7]: the_dict
Out[7]: {'witchcraft': 3, 'witches': 1, 'with': 1}

In [8]: json.dumps({"Frequencies": the_dict})
Out[8]: '{"Frequencies": {"with": 1, "witches": 1, "witchcraft": 3}}'
</code></pre>

python json