im need to convert it in list
[{"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"}]
without import json
CodePudding user response:
Let's assume your input data is already a list, and not a string
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"}]
Then, loop over items in dictionary (only element from the input list) and pass them as single dictionary in output list
output = [{key: value} for key, value in input[0].items()]
Output list is
[{'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'}]
CodePudding user response:
If you don't want to use the JSON module, the only other package to do so (that I know) is Pandas, which isn't bundled with Python, hence it's pip-only (pip install pandas
).
It has a pandas.read_json()
function, which takes a file name as its first argument.
So, you'll want to use it like this (assuming the stringified response is saved to the response
variable:
import pandas as pd
with open("response.json", "w") as f:
f.write(response)
parsed_resp = pd.read_json("response.json")
Despite the package being only available via pip, pandas.read_json()
also allows some automatic capabilities, like numpy = True
to save numeric arrays as NumPy arrays, convert_dates = True
allowing to automatically convert dates to machine-readable objects, etc.