8-Bit Borges
8-Bit Borges

Reputation: 10033

Python - printing dictionaries without commas

I am procesing an music APIand writing results to a file, like so:

for val, track_id in zip(values,list(track_ids)):
    #below
    if val < threshold:
       data = {"artist": sp.track(track_id)['artists'][0]['name'], "track":sp.track(track_id)['name'], "feature": filter_name, "value": val}
      #write to file
      with io.open('db/json' + '/' + user + '_' + product + '_' + filter_name + '.json', 'a', encoding='utf-8') as f:
           f.write(json.dumps(data, ensure_ascii=False, indent=4, sort_keys=True))

data is printed as follows:

}{
    "artist": "Radiohead", 
    "feature": "tempo", 
    "track": "Climbing Up the Walls", 
    "value": 78.653
}{
    "artist": "The Verve", 
    "feature": "tempo", 
    "track": "The Drugs Don't Work", 
    "value": 77.368
}{

the bottleneck is that, further down the code, I try to evaluate this file with eval, and it generates the error:

  File "<string>", line 6
    }{
     ^

how do I insert this 'comma to separate the dicionaries?

Upvotes: 0

Views: 1096

Answers (1)

Soviut
Soviut

Reputation: 91545

It looks like you're trying to write JSON data. If that's the case you can simply dump your dictionary to a file using the json module. You should first append all your data objects into a single music list. You can then encode that list to JSON and write it to a file.

import json

music = [
    {
        "artist": "Radiohead", 
        "feature": "tempo", 
        "track": "Climbing Up the Walls", 
        "value": 78.653
    },
    {
        "artist": "The Verve", 
        "feature": "tempo", 
        "track": "The Drugs Don't Work", 
        "value": 77.368
    }
]

with open('music.json') as f:
    json.dump(music, f, sort_keys=True, indent=4)

https://docs.python.org/2/library/json.html#json.dump

Additionally, you should NOT be using eval() if you can help it; Especially when reading random input from a file. It's incredibly fragile (as you've discovered) but it's also incredibly insecure. Someone could easily put malicious code into a file you're evaluating.

Instead, you should use json.load() to load the JSON from the file. This will ensure the file is properly formatted JSON and it does all the heavy lifting for you.

with open('music.json') as f:
    music = json.load(f)

Upvotes: 1

Related Questions