在使用 python 读取 avro 数据文件的 hadoop 流中,我使用的是输入格式,文档说输入键是 JSON 中的字符串表示。
-inputformat org.apache.avro.mapred.AvroAsTextInputFormat
映射器将其作为行输入获取:
line = "{u'three': u'3', u'two': u'2', u'one': u'1'}"
我如何解析这个字符串,以获得键值对?
最佳答案
我想这就是你需要的:
>>> line = "{u'three': u'3', u'two': u'2', u'one': u'1'}"
>>> line
"{u'three': u'3', u'two': u'2', u'one': u'1'}"
>>> import ast
>>> mydict = ast.literal_eval(line)
>>> mydict
{u'one': u'1', u'three': u'3', u'two': u'2'}
>>> for key in mydict:
print key, mydict[key]
one 1
three 3
two 2
>>>
关于python - 使用 python 流解析从 org.apache.avro.mapred.AvroAsTextInputFormat 生成的 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166477/