Retrieving responses from a JSON File
<p>I'm trying to pull some values out of an JSON file but it doesn't seem to be working.  Additionally, when I try to add print statements to see where it is blowing up, nothing prints.  Can anyone see any glaring reason why this isn't working?  The only thing I can think of is that it has something to do with the fact that I recently switched from a PC to a Mac and the files are stored as rtf's rather than txt's.  </p>

<pre><code>import glob2
import json

fdr = glob2.glob('/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/*.rtf')    #insert all rtf files in folder into list

for dr in fdr:        #loop through file list
    print(dr)
    ending = str(dr[57:])     #cut filename from pathname
    pe = ending.replace('.rtf', '')    #add filename to path
    f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv'     #format the file as csv
    f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe            #access rtf file
    print(f_n)

    file_path = 'f_n'
    file_out = 'f_quest'
    with open(file_path) as f_in, open(file_out) as f_out:
        data = json.load(f_in)
    print(data.keys())  # list the dicts keys

    q = 'vviq'
    response = data[q]['response']
    f_out.write('response')    #write responses to new .csv file
</code></pre>

<p>Your code outputs nothing because you create and open an empty file named <code>f_n</code> in the directory of the python script, then attempt to load it with the json module. </p>

<p>These are variables that are assigned to <em>string literals</em>, not the variables you previously defined. </p>

<pre><code>file_path = 'f_n'
file_out = 'f_quest'
</code></pre>

<p>These are variables that are assigned to <em>paths on your system</em></p>

<pre><code>f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv'     #format the file as csv
f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe            #access rtf file
</code></pre>

<p>I assume you are wanting to open the later? If that is the case, then the former variables are completely pointless. And you should give these variables to <code>open()</code>, but don't quote the variable name. </p>

<p>Also,  <code>open()</code> defaults to read mode, so you might want to fix that when you attempt to do <code>f_out.write('response')</code>,  which should be intended under the <code>with</code>, otherwise the file is closed, and again <code>'response'</code> is a string literal of the word "response" and not the <code>response</code> variable that you assigned in the previous line </p>

python json