How to parse JSON data keys and values in python?

时间:2015-06-25 19:16:16

标签: python json python-2.7

I have a variable called data. It contains following JSON value. data=['{"time":["1000","MS"],"What is your name?":["John"]}'] I want to separate keys and values from it and want output like following. Keys ----- time What is your name? Value: ------ 1000 MS John How to do it in python?

2 个答案:

答案 0 :(得分:3)

您可以使用json.loads来解析json字符串

>>> data=['{"time":["1000","MS"],"What is your name?":["John"]}']
>>> a_dict = json.loads(data[0])

>>> a_dict.keys()
[u'What is your name?', u'time']
>>> a_dict.values()
[[u'John'], [u'1000', u'MS']]

现在,您可以使用简单的for循环来打印所需的输出。

或者喜欢

>>> print '\n'.join(a_dict.keys())
What is your name?
time
>>> print '\n'.join( '\n'.join(x )for x in a_dict.values() )
John
1000
MS

答案 1 :(得分:0)

您还可以使用ast模块:

>>> import ast
>>> ast.literal_eval(data[0])
{'What is your name?': ['John'], 'time': ['1000', 'MS']}
>>> d=ast.literal_eval(data[0])
>>> print '\n'.join(d.keys())
What is your name?
time
>>> print '\n'.join([j for i in d.values() for j in i])
John
1000
MS