0

Now I have a string in format dict but as i can guess its a json format its look like:

{
   "gid":"1201400250397201",
   "memberships":[
      "can be nested objects",
      ...
   ],
   "name":"Name of task",
   "parent":{
      "gid":"1201400250397199",
      "name":"name of parent task"
   },
   "permalink_url":"https://url...."
}
  1. So first question: am i right? I used dumps() from json library but got unicode escape sequences, loads() didnt work for me, i got error "the JSON object must be str, bytes or bytearray, not dict".

  2. Second question: if its not json format, how can i get comfortable view? I did it: first of all i get dict-line, then I print a dictionary's key:

    for key in task:
        task
        print(task[key])
    

    output:

    1201400250397201
    []
    Name of task
    {'gid': '1201400250397199', 'name': ''name of parent task'}
    https://url....
    

At actually it would be great if I get something like that:

gid: 1201400250397201
name: Name of task
parent_name: 'Name of task' etc

But I dont know how to get it :(

Next question: as you can see for part "parent" (penultimate line) I also get dictionary, how can I extract it and get convenient format? Or maybe you have your comfortable methods?

jupiterbjy
  • 2,882
  • 1
  • 10
  • 28
hsgggs
  • 1
  • Python objects are not JSON. In order to pretty-print a Python object, use the [`pprint`](https://docs.python.org/3/library/pprint.html) module. – Jan Wilamowski Dec 13 '21 at 08:38
  • Does this answer your question? [How to pretty print nested dictionaries?](https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries) – Jan Wilamowski Dec 13 '21 at 08:41

1 Answers1

0

Like stated in your error, the object you are working with is already a dictionary. You can print it directly as json with json.dumps:

task = {'gid': '1201400250397201', 'memberships': [{}], 'name': 'Name of task', 'parent': {'gid': '1201400250397199', 'name': 'name of parent task'},'permalink_url': 'https://url....'}
print(json.dumps(task, indent=4))

Setting indent=4 makes it readable and you'll get:

{
    "gid": "1201400250397201",
    "memberships": [
        {}
    ],
    "name": "Name of task",
    "parent": {
        "gid": "1201400250397199",
        "name": "name of parent task"
    },
    "permalink_url": "https://url...."
}

If you don't want unicode characters to be escaped, add the argument ensure_ascii=False:

print(json.dumps(task, indent=4, ensure_ascii=False))
Tranbi
  • 11,407
  • 6
  • 16
  • 33