user227666
user227666

Reputation: 784

Parse json data

My data.json is

{"a":[{"b":{"c":{ "foo1":1, "foo2":2, "foo3":3, "foo4":4}}}],"d":[{"e":{"bar1":1, "bar2":2, "bar3":3, "bar4":4}}]}

I am able to list both key/pair values. My code is:

#! /usr/bin/python
import json
from pprint import pprint

 with open('data2.json') as data_file:    
   data = json.load(data_file)
 pprint(data["d"][0]["e"])

Which gives me:

{u'bar1': 1, u'bar2': 2, u'bar3': 3, u'bar4': 4}

But I want to display only the keys without any quotes and u like this:

bar1, bar2, bar3, bar4

Can anybody suggest anything? It need not be only in python, can be in shell script also.

Upvotes: 1

Views: 118

Answers (3)

bnjmn
bnjmn

Reputation: 4584

data["d"][0]["e"] returns a dict. In python2, You could use this to get the keys of that dict with something like this:

k = data["d"][0]["e"].keys()
print(", ".join(k))

In python3, wrap k in a list like this

k = list(data["d"][0]["e"].keys())
print(", ".join(k))

Even simpler, join will iterate over the keys of the dict.

print(", ".join(data["d"][0]["e"]))

Thanks to @thefourtheye for pointing this out.

Upvotes: 0

ely
ely

Reputation: 77494

The keys of this object are instances of the unicode string class. Given this, the default printing behavior of the dict instance for which they are the keys will print them as you show in your post.

This is because the dict implementation of representing its contents as a string (__repr__ and/or __str__) seeks to show you what objects reside in the dict, not what the string representation of those objects looks like. This is an important distinction, for example:

In [86]: print u'hi'
hi

In [87]: x = u'hi'

In [88]: x
Out[88]: u'hi'

In [89]: print x

hi

This should work for you, assuming that printing the keys together as a comma-separated unicode is fine:

print ", ".join(data["d"][0]["e"])

You can achieve this using the keys member function from dict too, but it's not strictly necessary.

Upvotes: 1

Kai Keliikuli
Kai Keliikuli

Reputation: 308

print ', '.join((data["d"][0]["e"].keys()))

Upvotes: 0

Related Questions