Python-没有JSON模块的JSON



im需要在列表中进行转换

[{"name":"Perm District","local_names":{"hr":"Perm","cs":"Perm","ca":"Perm","en":"Perm District","fr":"Perm","ro":"Perm","kn":"ಪೆರ್ಮ್","es":"Perm","pl":"Perm","ru":"Пермский городской округ","zh":"彼尔姆","ja":"ペルミ管区","feature_name":"Perm","pt":"Perm","de":"Stadtkreis Perm","lv":"Perma","et":"Perm","hi":"पॆर्म्","ko":"페름","uk":"Перм","fi":"Perm","ar":"دائرة المدينة بيرم","ku":"Perm","ascii":"Perm","hu":"Perm","oc":"Perm","lt":"Permė","sk":"Perm"},"lat":58.014965,"lon":56.246723,"country":"RU","state":"Perm Krai"}]

不导入json

假设您的输入数据已经是一个列表,而不是字符串

input = [{"name":"Perm District","local_names":{"hr":"Perm","cs":"Perm","ca":"Perm","en":"Perm District","fr":"Perm","ro":"Perm","kn":"ಪೆರ್ಮ್","es":"Perm","pl":"Perm","ru":"Пермский городской округ","zh":"彼尔姆","ja":"ペルミ管区","feature_name":"Perm","pt":"Perm","de":"Stadtkreis Perm","lv":"Perma","et":"Perm","hi":"पॆर्म्","ko":"페름","uk":"Перм","fi":"Perm","ar":"دائرة المدينة بيرم","ku":"Perm","ascii":"Perm","hu":"Perm","oc":"Perm","lt":"Permė","sk":"Perm"},"lat":58.014965,"lon":56.246723,"country":"RU","state":"Perm Krai"}]

然后,循环遍历字典中的项目(仅输入列表中的元素(,并将它们作为输出列表中的单个字典传递

output = [{key: value} for key, value in input[0].items()]

输出列表为

[{'name': 'Perm District'}, {'local_names': {'hr': 'Perm', 'cs': 'Perm', 'ca': 'Perm', 'en': 'Perm District', 'fr': 'Perm', 'ro': 'Perm', 'kn': 'ಪೆರ್ಮ್', 'es': 'Perm', 'pl': 'Perm', 'ru': 'Пермский городской округ', 'zh': '彼尔姆', 'ja': 'ペルミ管区', 'feature_name': 'Perm', 'pt': 'Perm', 'de': 'Stadtkreis Perm', 'lv': 'Perma', 'et': 'Perm', 'hi': 'पॆर्म्', 'ko': '페름', 'uk': 'Перм', 'fi': 'Perm', 'ar': 'دائرة المدينة بيرم', 'ku': 'Perm', 'ascii': 'Perm', 'hu': 'Perm', 'oc': 'Perm', 'lt': 'Permė', 'sk': 'Perm'}}, {'lat': 58.014965}, {'lon': 56.246723}, {'country': 'RU'}, {'state': 'Perm Krai'}]

如果您不想使用JSON模块,唯一可以使用的其他包(据我所知(是Pandas,它没有与Python绑定,因此它只使用pip(pip install pandas(。

它有一个pandas.read_json()函数,它将文件名作为第一个参数。

因此,您需要这样使用它(假设字符串化的响应保存到response变量:

import pandas as pd
with open("response.json", "w") as f:
f.write(response)
parsed_resp = pd.read_json("response.json")

尽管该包只能通过pip获得,但pandas.read_json()也允许一些自动功能,如numpy = True将数字数组保存为NumPy数组,convert_dates = True允许自动将日期转换为机器可读对象,等等。

相关内容

  • 没有找到相关文章

最新更新