Mohammad Zamanian
Mohammad Zamanian

Reputation: 771

how to print json data

I have following json file and python code and i need output example...

json file

{"b": [{"1": "add"},{"2": "act"}],
"p": [{"add": "added"},{"act": "acted"}],
"pp": [{"add": "added"},{"act": "acted"}],
"s": [{"add": "adds"},{"act": "acts"}],
"ing": [{"add": "adding"},{"act": "acting"}]}

python

import json
data = json.load(open('jsonfile.json'))
#print data

out put example

>> b
>> p
>> pp
>> s
>> ing

any ideas how to do that?

Upvotes: 0

Views: 478

Answers (4)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160647

Simply unpack the keys with * in a print call, this provides the keys as positional arguments to print; use sep = '\n' if you want each key on a different line:

print(*data.keys(), sep= '\n')

This will print out:

b
pp
p
ing
s

As noted by @WayneWerner print(*data, sep='\n') is in effect like calling data.keys() and achieves the same result.

Upvotes: 2

Wayne Werner
Wayne Werner

Reputation: 51897

For the sake of completeness:

d = {'p': 'pstuff', 'pp': 'ppstuff', 'b': 'bstuff', 's': 'sstuff'}
print('\n'.join(d))

Works in any version of Python. If you care about order:

print('\n'.join(sorted(d)))

Though in all honesty, I'd probably do Jim's approach:

print(*d, sep='\n'))

Upvotes: 2

BPL
BPL

Reputation: 9863

Here's a working example (it's emulating your file using io.StringIO):

import json
import io

jsonfile_json = io.StringIO("""
{
    "b": [{"1": "add"}, {"2": "act"}],
    "p": [{"add": "added"}, {"act": "acted"}],
    "pp": [{"add": "added"}, {"act": "acted"}],
    "s": [{"add": "adds"}, {"act": "acts"}],
    "ing": [{"add": "adding"}, {"act": "acting"}]
}
""")

data = json.load(jsonfile_json)

for k in data.keys():
    print(k)

As you can see, the answer to your question is using keys() method

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599956

This doesn't have anything to do with JSON. You have a dictionary, and you want to print the keys, which you can do with data.keys().

Upvotes: 4

Related Questions