Predictive Hacks

Difference Between json.dumps and json.loads

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'}]}

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s