T
T
Timebird2016-10-03 14:51:41
Python
Timebird, 2016-10-03 14:51:41

How to translate JSON to PythonObj without bugs?

There is a function:

def load_data(filepath):

    data = []
    with open(filepath) as f:
        for line in f:
            data.append(json.loads(line)) #convert JSON to Python object
    print(data)
    return data

It loads data from a JSON file.
And it works, but the output is something like this:
{u'type': u'Point', u'coordinates': [37.717115000077776, 55.78262800012168]}, u'SocialPrivileges': u'\u043d\u0435\u0442', u'AdmArea': u'\u0412\u043e\u0441\u0442\u043e\u0447\u043d\u044b\u0439 \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u043e\u043a\u0440\u0443\u0433', u'SeatsCount': 177}, u'Id': u'4644e029-30f7-4e9c-8a1e-1ec20595f564', u'Number': 515}]]

Where to put the parameters here ensure_ascii=False, sort_keys=True, indent=4?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BogBel, 2016-10-03
@Timebird

import json
with open(file_path) as file:
   data = json.load(file)

I don't know if this is the answer to your question, but when there is a task to read valid JSON from a file, use json.load.
json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
Taken from
the docs. Usually these parameters (ensure_ascii, sort_keys, indent) are used to beautifully write to a json file via json.dumps()
. If you need to beautifully print a PythonObject to the console, then I advise you to pay attention to
pprint
from pprint import pprint
data = {'key1': 'value1', 'key2': {'key2.1': 'value2.1', 'key2.2': {'key2.2.1': 'value2.2.1', 'key2.2.2': 'value2.2.2'}, 'key2.3': 'value2.3'}, 'key3': 'value3'}
>>> pprint(data)
{'key1': 'value1',
 'key2': {'key2.1': 'value2.1',
          'key2.2': {'key2.2.1': 'value2.2.1', 'key2.2.2': 'value2.2.2'},
          'key2.3': 'value2.3'},
 'key3': 'value3'}

PS most likely the problem is in opening the file, try passing an additional encoding parameter to open

D
Dmitry Azarenko, 2016-10-04
@adv-tsk

It will transform normally for you. You can display it on the screen without using json.dumps like this .

S
Sergey Pankov, 2016-10-06
@trapwalker

Dmitry Azarenko brought a great option.
You can also dump d json with the parameters you specify, what you print and print the result of the dump, not repr

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question