How To Convert JSON Object to String In Python

Python supports JavaScript Object Notation (JSON) format to store and interchange web application or server data. JSON file is written in script format that uses java script. In python, JSON is used through a predefined package named JSON.  A JSON object is similar to a python dictionary that is defined using double quoted strings as key-value pairs in the curly braces i.e. ‘{“key”:“value” }’. A syntax and example to  create a  JSON object is given below.

 Syntax:       

 JSONObjectName = ‘{ “Key1”: “value1”, “Key2”: “value2”, .., “KeyN”: “valueN”}’

Example:

 StudentData= ‘{“name”: “Sunny”, “Gender”: “Male”, “Age”:22, “CGPA”:8.70}’

An above example shows creating a JSON named StudentData which stores data of students such as name, gender, age and cgpa. A python code to create a JSON is demonstrated below.

Python Code to Create a JSON:

# Python code to create a JSON object
import json  # import JSON package
StudentData= '{"Name": "Sunny","Gender": "Male", "Age":22, "CGPA":8.70}'           # It create StudentData JSON object
print(StudentData)  # It display data in JSON format  

Output:

{"Name": "Sunny", "Gender": "Male", "Age": 22, "CGPA": 8.7}

Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • Import an in-built package i.e. JSON.
  • A JSON object  named StudentData is created which contains the name, gender age and cgpa of a student.
  • A JSON object is displayed.

Why Is There A Need To Convert JSON Object to String  In Python

  • Web application or server data processing: Web applications or servers get and transmit data in JSON formats. To store and process JSON data, we need to convert it into python strings. This conversion enables an easy and convenient way to work with JSON objects in string form.
  • Send JSON object on web server: A JSON object can not be sent to a web server directly because HTTP does not understand binary format. Therefore a JSON object is required to convert into python strings.           

Approaches: How to Convert JSON Object to String

To convert JSON objects to string, numerous methods are available. There are some methods listed below. 

  • Approach-1: Using dumps() method
  • Approach-2: Using an API:request.get() method 
  • Approach-3: Using str() method
  • Approach-4: Using repr() method

Approach-1: Using dumps() method

A JSON object may be converted into string using a predefined function of the JSON library i.e. dumps(). Dumps() function takes a JSON object as an input argument and returns a python string as output. A python code to convert JSON to string using dumps() function demonstrated below. 

# Python code to convert a JSON object to String
import json  # import JSON package
StudentData= '{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}'              # It create StudentData JSON Object
print('Data Display in JSON format:')
print(StudentData)  # It display JSON format
json.dumps(StudentData)     # It convert JSON object in to string using dumps() function
print('Data Display in String format:')
print(StudentData)     # it display converted string

Output:

Data Display in JSON format:
{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}
Data Display in String format:
{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}

 Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • Import an in-built package i.e. JSON.
  • A JSON object  named StudentData is created which contains the name, gender age and cgpa of a student.
  • A JSON object is converted to string using dumps() function.
  • A JSON format and String format data is displayed.

Approach-2: Using an API:request.get() method

An API get method of request package is another method for converting JSON objects into string. Get() method of request package extracts JSON data from the web applications through specific URLs. A python code to convert JSON to string using get() function demonstrated below. 

# Python code to convert a JSON object to String
import json  # import JSON package
import requests  # import requests package
js = requests.get("https://www.google.com/search?q=how+to+convert+JSON+object+to+string+in+python&sxsrf=AJOqlzWSEyrWZBcUlMYrq_xwWhCTn9r1GQ%3A1677056997126&ei=5dv1Y9qfB9CcseMPqqCxgA4&ved=0ahUKEwiaptOU5Kj9AhVQTmwGHSpQDOAQ4dUDCA8&uact=5&oq=how+to+convert+JSON+object+to+string+in+python&gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCAAQkQIyDAgAEBYQHhDxBBCLAzIJCAAQFhAeEIsDMggIABCGAxCLAzIICAAQhgMQiwM6CggAEEcQ1gQQsAM6BQgAEIAESgQIQRgAUJIGWL8UYNUXaAFwAXgAgAGZAYgBkwuSAQQwLjEwmAEAoAEByAEIuAEDwAEB&sclient=gws-wiz-serp")    # It retrieve JSON data
print(js)  # It display JSON format
data= json.dumps(js.text)
print('Data Display in JSON format:')
print(data)     
print('Data Display in String format:')
print(data)

Output:

Data Display in String format:
"<!doctype html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta content=\"/images/branding/googleg/1x/googleg_standard_color_128dp.png\" itemprop=\"image\"><title>how to convert JSON object to string in python - Google Search</title><script nonce=\"2pbkQDm8FDoppeh3qMwHMA\">(function(){\ndocument.documentElement.addEventListener(\"submit\",function(b){var a;if(a=b.target){var c=a.getAttribute(\"data-submitfalse\");a=\"1\"===c||\"q\"===c&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener(\"click\",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if(\"A\"===a.tagName){a=\"1\"===a.getAttribute(\"data-nohref\");break a}a=!1}a&&b.preventDefault()},!0);}).call(this);(function(){var a=window.performance;window.start=Date.now();a:{var b=window;if(a){var c=a.timing;if(c){var d=c.navigationStart,f=c.responseStart;if(f>d&&f<=window.start){window.start=f;b.wsrt=f-d;break a}}a.now&&(b.wsrt=Math.floor(a.now()))}}window.google=window.google||{};var h=function(g){g&&g.target.setAttribute(\"data-iml\",String(Date.now()))};document.documentElement.addEventListener(\"load\",h,!0);google.rglh=function(){document.documentElement.removeEventListener(\"load\",h,!0)};}).call(this);(function(){window._skwEvts=[];})();(function(){window.google.erd={jsr:1,bv:1747,de:true};})();(function(){var sdo=false;var mei=10;\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||\"Error loading script\"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var c=\"/gen_204?atyp=i&ei=\"+b(google.kEI);google.kEXPI&&(c+=\"&jexpid=\"+b(google.kEXPI));c+=\"&srcpg=\"+b(google.sn)+\"&jsr=\"+b(t.jsr)+\"&bver=\"+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+=\"&line=\"+f);var g=\na.fileName;g&&(0<g.indexOf(\"-extension:/\")&&(e=3),c+=\"&script=\"+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split(\"\\n\")[f],c+=\"&cad=\"+b(f?f.substring(0,300):\"No script found.\")));c+=\"&jsel=\"+e;for(var u in d)c+=\"&\",c+=b(u),c+=\"=\",c+=b(d[u]);c=c+\"&emsg=\"+b(a.name+\": \"+a.message);c=c+\"&jsst=\"+b(a.stack||\"N/A\");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,\"\",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||\"lineNumber\"in a||(a.lineNumber=d),void 0===b||\"fileName\"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,\"SyntaxError\"===a.name||\"SyntaxError\"===a.message.substring(0,11)||-1!==a.message.indexOf(\"Script error\")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();(function(){var c=[],e=0;window.ping=function(b){-1==b.indexOf(\"&zx\")&&(b+=\"&zx=\"+Date.now());var a=new Image,d=e++;c[d]=a;a.onerror=a.onload=a.onabort=function(){delete c[d]};a.src=b};}).call(this);</script><style>a{color:#1a0dab;text-decoration:none;tap-highlight-color:rgba(0,0,0,.10)}a:visited{color:#4b11a8}a:hover{text-decoration:underline}img{border:0}html{font-family:arial,sans-serif;font-size:14px;line-height:20px;text-size-adjust:100%;color:#3c4043;word-wrap:break-word;background-color:#fff}.bRsWnc{background-color:#fff;border-top:1px solid #dadce0;height:39px;overflow:hidden}.N6RWV{height:51px;overflow-scrolling:touch;overflow-x:auto;overflow-y:hidden}.Uv67qb{box-pack:justify;font-size:12px;line-height:37px;justify-content:space-between;justify-content:space-between}.Uv67qb a,.Uv67qb span{color:#70757a;display:block;flex:none;padding:0 16px;text-align:center;text-transform:uppercase;}span.OXXup{border-bottom:2px solid

Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • Import an in-built package i.e. JSON and requests.
  • A JSON object is created which retrieves data from a web application by a given URL in the get() function.
  • A JSON object is converted to string using dumps() function.
  • A String format data is displayed.

Approach-3: Using str() method

Python str() in-built function enables convert any object into string. Though, we can also convert JSON objects to string using str() function.  A python code to convert JSON objects to string using str() function demonstrated below. 

# Python code to convert a JSON object to String
import json  # import JSON package
StudentData= '{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}'              # It create StudentData JSON Object
print('Data Display in JSON format:')
print(StudentData)  # It display JSON format
StudentData=str(StudentData)     # It convert JSON object in to string using str() function
print('Data Display in String format:')
print(StudentData)     # it display converted string

Output:

Data Display in JSON format:
{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}
Data Display in String format:
{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}

 Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • Import an in-built package i.e. JSON.
  • A JSON object  named StudentData is created which contains the name, gender age and cgpa of a student.
  • A JSON object is converted to string using str() function.
  • A JSON format and String format data is displayed.

Approach-4: Using repr() method

With the help of repr() in-built function,  an object is converted to string. Though, a JSON object may convert to string using repr() function.  A python code to convert JSON objects to string using repr() function demonstrated below. 

# Python code to convert a JSON object to String using repr() function
import json  # import JSON package
StudentData= '{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}'              # It create StudentData JSON Object
print('Data Display in JSON format:')
print(StudentData)  # It display JSON format
StudentData=repr(StudentData)     # It convert JSON object in to string using repr() function
print('Data Display in String format:')
print(StudentData)     # it display converted string

Output:

Data Display in JSON format:
{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}
Data Display in String format:
'{"Name": "Sunny","Gender": "Male", "Age":22,"CGPA":8.70}'

 Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • Import an in-built package i.e. JSON.
  • A JSON object  named StudentData is created which contains the name, gender age and cgpa of a student.
  • A JSON object is converted to string using repr() function.
  • A JSON format and String format data is displayed.

Best Approach- dumps() Method

JSON in-bult function i.e. dumps() method is considered as best suitable method to convert JSON object to string because of following factors.

  • This method converts valid JSON strings. It means the dumps() method replaces None with NULL to produce a valid string.
  • It also supports conversion of  date time objects to valid strings.

Sample problem related to filtering a list in Python

Sample Problem-1: Using Approach-1

Problem Definition: Create a python code that demonstrates conversion of JSON object to string using dumps() method. For this, create a JSON object which stores information about the player which contains name, age, maxscore, average score etc. 

Solution (Python Code):

Python code to convert a JSON object to String using approach-1
import json  # import JSON package
Player= '{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}'              # It create Player JSON Object
print('Data Display in JSON format:')
print(Player)  # It display JSON format
json.dumps(Player)     # It convert JSON object in to string using dumps() function
print('Data Display in String format:')
print(Player)     # it display converted string

Output:

Data Display in JSON format:
{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}
Data Display in String format:
{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}

Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • An in-built package i.e. JSON is import
  • A JSON object  named Player is created which contains the name, age, maximum score and average score of a player.
  • A JSON object is converted to string using dumps() function.
  • A JSON format and String format data is displayed.

Sample Problem-2:Using Approach-2

Consider a JSON object that retrieves from the given url i.e.  https://colab.research.google.com/drive/1cK98PUnq4HxUaanAB252fRABQatg7y1S?authuser=1#scrollTo=CoNgA4QaIWJJ. Create a python code that demonstrates conversion of JSON objects to string using an API:requests.get() method.

Solution (Python Code):

# Python code to convert a JSON object to String using approach-2
import json  # import JSON package
import requests  # import requests package
webdata = requests.get("https://colab.research.google.com/drive/1cK98PUnq4HxUaanAB252fRABQatg7y1S?authuser=1#scrollTo=CoNgA4QaIWJJ")    # It retrieve JSON data
print(webdata)  # It display JSON format
data= json.dumps(webdata.text)
print('Data Display in JSON format:')
print(data)

 Output:

Data Display in JSON format:
"<!DOCTYPE html><html lang=\"en\"><head><script nonce=\"vbLxZF6845Ih66nwNmLLqg==\">\n      document.addEventListener('keydown', (e) => {\n        // Stop propagation on ESC because otherwise it will halt outbound XHRs\n        // See b/131755324 for more info.\n        if (e.key === 'Escape') {\n          e.stopPropagation();\n          e.preventDefault();\n        }\n      });\n    </script><meta name=\"referrer\" content=\"origin\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Google Colab</title><link rel=\"search\" type=\"application/opensearchdescription+xml\" href=\"/opensearch.xml\" title=\"Google Colaboratory\"/><style>.gb_7a:not(.gb_Od){font:13px/27px Roboto,Arial,sans-serif;z-index:986}@-webkit-keyframes gb__a{0%{opacity:0}50%{opacity:1}}@-moz-keyframes gb__a{0%{opacity:0}50%{opacity:1}}@-o-keyframes gb__a{0%{opacity:0}50%{opacity:1}}@keyframes gb__a{0%{opacity:0}50%{opacity:1}}a.gb_ea{border:none;color:#4285f4;cursor:default;font-weight:bold;outline:none;posit

 Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • An in-built package i.e. JSON and requests are used here.
  • A JSON object is created which retrieves data from a web application by a given URL in the get() function.
  • A JSON object is converted to string using dumps() function.
  • A String format data is displayed.

Sample Problem-3: Using Approach-3

Consider a JSON object named player which contains name, age, maximum score and average score. Create a python code that demonstrates to find the maximum score of the player through converting a JSON object to string using str() function.

# Python code to convert a JSON object to String using approach-3
import json  # import JSON package
Player= '{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}'              # It create Player JSON Object
print('Data Display in JSON format:')
print(Player)  # It display JSON format
Player=str(Player)     # It convert JSON object in to string using str() function
print('Data Display in String format:')
print(Player)     # it display converted string
print('Maximum score of player is:',int(Player[38:41]))     # it display maximum score of player

Output:

Data Display in JSON format:
{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}
Data Display in String format:
{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}
Maximum score of player is: 210

 Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • An in-built package i.e. JSON is import
  • A JSON object  named Player is created which contains the name, age, maximum score and average score of a player.
  • A JSON object is converted to string using str() function.
  • A JSON format and String format data is displayed. It also displays the maximum score of the player.

Sample Problem-4: Using Approach-4

Create a python code that demonstrates converting the name of the player into capital letters and to find the age of the player via conversion of JSON object named player to string using repr() method.    

# Python code to convert a JSON object to String using approach-4
import json  # import JSON package
Player= '{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}'   # It create Player JSON Object
print('Data Display in JSON format:')
print(Player)  # It display JSON format
Player=repr(Player)     # It convert JSON object in to string using repr() function
print('Data Display in String format:')
print(Player)     # it display converted string
print(Player[11:17].capitalize)    # It display name of player in capital letters
print('Age of player is:',int(Player[25:27]))     # It display maximum score of player

Output:

Data Display in JSON format:
{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}
Data Display in String format:
'{"Name": "Maggie","Age":20,"MaxScore":210, "AverageScore":70.45}'
<built-in method capitalize of str object at 0x7f1ae036aab0>
Age of player is: 20

Code Explanation:

  • Comment line tells the goal of the program to programmers.
  • An in-built package i.e. JSON is import
  • A JSON object  named Player is created which contains the name, age, maximum score and average score of a player.
  • A JSON object is converted to string using repr() function.
  • A JSON format and String format data is displayed. It also displays the name of the player in capital letters and age.

Conclusion

Generally, web applications or servers store and send data in JavaScript Object Notation (JSON) format. Python supports JSON data processing and conversion into python objects. JSON objects may be converted to string using many approaches such as dumps(), API:requests.get(), str() and repr() functions.  Among all, conversion of JSON objects to string through the dumps() function is considered the best approach. Here, all approaches for the conversion of JSON objects to string have been presented with python code, output and its explanation.