json.loads
take a string as input and returns a dictionary as output where the json.dumps
take a dictionary as input and returns a string as output.
For example:
import json test_string = """ {"data":[{"id": 5001, "type": "A"},{"id": 5002, "type": "D"}, {"id": 5003, "type": "D"},{"id": 5004, "type": "D"}, {"id": 5005, "type": "C"},{"id": 5006, "type": "C"}, {"id": 5007, "type": "C"}]} """ test_dict = {"data":[{"id": 5001, "type": "A"},{"id": 5002, "type": "D"}, {"id": 5003, "type": "D"},{"id": 5004, "type": "D"}, {"id": 5005, "type": "C"},{"id": 5006, "type": "C"}, {"id": 5007, "type": "C"}]}
Let’s load them, starting with the string
json.loads(test_string)
{'data': [{'id': 5001, 'type': 'A'},
{'id': 5002, 'type': 'D'},
{'id': 5003, 'type': 'D'},
{'id': 5004, 'type': 'D'},
{'id': 5005, 'type': 'C'},
{'id': 5006, 'type': 'C'},
{'id': 5007, 'type': 'C'}]}
Let’s load the dictionary.
json.dumps(test_dict)
'{"data": [{"id": 5001, "type": "A"}, {"id": 5002, "type": "D"}, {"id": 5003, "type": "D"}, {"id": 5004, "type": "D"}, {"id": 5005, "type": "C"}, {"id": 5006, "type": "C"}, {"id": 5007, "type": "C"}]}'
As you expected, if we convert the dictionary to string, then we can use the json.loads
. For example:
json.loads(json.dumps(test_dict))
{'data': [{'id': 5001, 'type': 'A'},
{'id': 5002, 'type': 'D'},
{'id': 5003, 'type': 'D'},
{'id': 5004, 'type': 'D'},
{'id': 5005, 'type': 'C'},
{'id': 5006, 'type': 'C'},
{'id': 5007, 'type': 'C'}]}