简体   繁体   English

遍历数据框的json python 2

[英]Looping through a dataframe a json python 2

I am new to python 2 and I want to loop through a json generated by a query and return same strings: This is my json: 我是python 2的新手,我想遍历查询生成的json并返回相同的字符串:这是我的json:

"{\\"Machine\\":{\\"0\\":\\"Mach1\\",\\"1\\":\\"Mach2\\",\\"2\\":\\"Mach3\\",\\"3\\":\\"Mach4\\",\\"4\\":\\"Mach5\\"}}" “ {\\” Machine \\“:{\\” 0 \\“:\\” Mach1 \\“,\\” 1 \\“:\\” Mach2 \\“,\\” 2 \\“:\\” Mach3 \\“,\\” 3 \\“ :\\“ Mach4 \\”,\\“ 4 \\”:\\“ Mach5 \\”}}“

What I don't understand is wich is the key here and how can I loop to get a result like this: 我不明白这是关键,我如何循环获得这样的结果:

Mach1
Mach2
Mach3
..

Or even just Mach1. 甚至只是Mach1。 I've tried this: 我已经试过了:

def printDict(dict):
    for key,v, value in d.iteritems():
        if type(v) is dict:
            printDict(v)
        else:
            print "{0} : {1}".

But doesn't seem to work 但似乎不起作用

First mistake: 第一个错误:

def printDict(dict):
    ...
    if type(v) is dict:

dict is no longer the built-in dictionary type, you've overwritten it locally. dict不再是内置字典的类型,您已在本地将其覆盖。 Also type(v) is dict is not a good way to check if something is an instance of something else (it doesn't take inheritance into account). 同样, type(v) is dict并不是检查某物是否为其他物的实例的好方法(它没有考虑继承)。

Second mistake: 第二个错误:

for key,v, value in d.iteritems():

.iteritems() method returns a sequence of pairs, not triples. .iteritems()方法返回一个成对的序列,而不是三元组。 Also d is an undefined local variable. d是未定义的局部变量。

Finally 最后

print "{0} : {1}".

is a syntax error. 是语法错误。

Is this what you are looking for: 这是你想要的:

def print_dict(dct):
    for key, value in dct.iteritems():
        if isinstance(value, dict):
            print_dict(value)
        else:
            print '{0} : {1}'.format(key, value)

Also if you start from raw JSON (ie a string) then you have to deserialize it first: 另外,如果您从原始JSON(即字符串)开始,则必须先反序列化它:

import json
dct = json.loads(my_json)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM