Convert string to JSON in PythonBefore taking a deep dive into the topic, let us have a glance on what strings are and what is JSON? Strings: are a sequence of characters that are denoted using inverted commas ”. They are immutable which means they cannot be changed once declared. JSON: stands for “JavaScript Object Notation”, the JSON files consist of text that can be easily read by humans and is present in the form of attribute-value pairs. The extension of JSON files is “.json” Let us have a look at the first approach of converting a string to json in Python. The following program illustrates the same. Output: The declared dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} It's type is <class 'str'> The resultant dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} The type of resultant dictionary is <class 'dict'> Explanation: It’s time to see the explanation so that our logic becomes clear-
Using eval()Output: The declared dictionary is {'C_code': 1, 'C++_code' : 26, 'Java_code' : 17, 'Python_code' : 28} Its type is <class 'str'> The resultant dictionary is {'C_code': 1, 'C++_code': 26, 'Java_code': 17, 'Python_code': 28} The type of resultant dictionary is <class 'dict'> Explanation: Let us understand what we have done in the above program.
Fetching valuesFinally, in the last program we will fetch the values after the conversion of string to json. Let’s have a look at it. Output: 1 17 We can observe the following things in the output-
ConclusionIn this Tutorial, we learned how to convert a string to json using Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263403.html