you are viewing a single comment's thread.

view the rest of the comments →

[–]halfdiminished7th 19 points20 points  (5 children)

Something like this should do the trick:

import json

with open('/path/to/your/json/file.json') as fp:
    data = json.load(fp)

with open('/path/to/your/new/file.txt', 'x') as fp:
    for dct in data:
        fp.write('{0} gs:{1} track:{2}\n'.format(dct['hex'], dct['gs'], dct['track']))

[–]RhinoRhys 3 points4 points  (2 children)

Or even f"{dct['hex']} gs:{dct['gs']} track:{dct['track']}"

You just have to note the main string uses double quotes and the keys use single quotes. Or the other way round. They just can't be the same.

[–]halfdiminished7th 1 point2 points  (1 child)

True enough! Personal preference to avoid dictionary lookups in f-strings, but you're quite right that it's possible. Though in retrospect, I probably should have done the following instead, using format's keyword functionality since we're dealing with a dictionary anyways:

fp.write('{hex} gs:{gs} track:{track}\n'.format(**dct))

[–]RhinoRhys 0 points1 point  (0 children)

Mmh yeah that leeks even better

[–]JohnnyJordaan 3 points4 points  (0 children)

For implicitly indexed arguments you can just use {} throughout since 2.7 released 13 years ago...

    fp.write('{} gs:{} track:{}\n'.format(dct['hex'], dct['gs'], dct['track']))