Movatterモバイル変換


[0]ホーム

URL:


Open In App

Data is transmitted across platforms using API calls. Data is mostly retrieved in JSON format. We can convert the obtained JSON data into String data for the ease of storing and working with it.Pythonprovides built-in support for working with JSON through thejson module. We can convert JSON data into a string using thejson.dumps()method.

Let's see how to convert JSON to String.

Json to String on dummy data using "json.dumps"

This code creates a Python dictionary and converts it into a JSON string using json.dumps(). The result is printed along with its type, confirming that the output is now a string.

Python
importjson# create a sample jsona={"name":"GeeksforGeeks","Topic":"Json to String","Method":1}y=json.dumps(a)print(y)print(type(y))

Output: 

jsonToString

Explanation:

  • json.dumps(a) converts thedictionarya into a JSON-formatted string.
  • print(y) prints the JSON string.
  • print(type(y))prints the type of the variable y, which will be <class 'str'> since the JSON data is now astring.

Json to String using an API using requests and "json.dumps"

This code makes a GET request to a dummy API to fetch employee data, converts the JSON response into a Python dictionary using json.loads(), and then converts it back into a JSON string using json.dumps(). The string is printed along with its type.

Python
importjsonimportrequests# Get dummy data using an APIres=requests.get("http://dummy.restapiexample.com/api/v1/employees")# Convert data to dictd=json.loads(res.text)# Convert dict to stringd=json.dumps(d)print(d)print(type(d))

Output: 

Explanation:

  • requests.get() fetches data from the API.
  • json.loads(res.text) converts the JSON string to a dictionary.
  • json.dumps(d) converts the dictionary back to a JSON string.

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp