SlideShare a Scribd company logo
JSON_FIles-Py (2).pptx
What is JSON ?
• JSON (JavaScript Object Notation) is a popular data format used for representing structured data. It's common to
transmit and receive data between a server and web application in JSON format.
• JSON was inspired by the JavaScript programming language, but it's not tied to only one language.
• Most modern programming languages have libraries for parsing and generating JSON data.
Why do we use JSON ?
• JSON has a more compact style than XML which was the format of
choice years ago. The light-weight approach can make significant
improvements.
• The XML software parsing process can take a long time. JSON uses
less data overall, so you reduce the cost and increase the parsing
speed.
• The JSON structure is straight forward and often more readable.
Basic JSON syntax
• In JSON, data is written in key-value pairs, like so:
"first_name": "Katie"
• Data is enclosed in double quotation marks and the key-value pair is separated
by a colon.
• There can be more than one key-value pair and each one is separated by a
comma:
"first_name": "Katie", "last_name": "Rodgers“
The example above showed an object, a collection of multiple key-value pairs.
Objects are inside curly braces:
{
"first_name": "Katie",
"last_name": "Rodgers"
}
Another example of JSON-formatted data is as follows:
{
"name": "Frank",
"age": 39,
"isEmployed": true
}
We can also create arrays, an ordered list of values, with JSON. In that
case, arrays are contained inside square brackets:
[
{
"first_name": "Katie",
"last_name": "Rodgers"
},
{
"first_name": "Naomi",
"last_name": "Green"
},
]
// or:
{
"employee": [
{
"first_name": "Katie",
"last_name": "Rodgers"
},
{
"first_name": "Naomi",
"last_name": "Green"
},
]
}
//this created an 'employee' object that has 2 records.
// It defines the first name and last name of an employee
In Python, JSON exists as a string. For example:
p = '{"name": "Bob", "languages": ["Python", "Java"]}'
It's also common to store a JSON object in a file.
Python and JSON
• Python makes it simple to work with JSON files.
• Python supports JSON through a built-in package called JSON.
• To use this feature, we import the JSON package in Python script. in order to use this
module is to import it:
import json
• This library mainly parses JSON from files or strings. It also parses JSON into a
dictionary or list in Python and vice versa, that is converting a Python dictionary or
list into JSON strings.
• The text in JSON is done through quoted-string which contains the value in key-
value mapping within { }.
• It is similar to the dictionary in Python.
JSON to Python (Decoding)
• JSON string decoding is done with the help of method
json.loads() & json.load() of JSON library in Python.
• Reading JSON means converting JSON into a Python value (object).
The json library parses JSON into a dictionary or list in Python.
JSON to Python
• Example 1: Python JSON to dict
• we use the loads() function (load from a string) to parse a JSON string and
the method returns a dictionary.
Here, jsonData is a JSON string, and jsonToPython is a dictionary.
• That is, the data is returned as a Python dictionary (JSON
object data structure).
• So, the statement print jsonToPython[‘name’] returns ‘Frank’
Note: In the above programs, the objects in JSON are converted to dictionaries in Python.
Example 2:
Example 3:
Decoding JSON File or Parsing JSON file in Python(Reading
JSON from a file using Python)
Let us see how to read JSON file in Python with Python parse JSON
example:
NOTE: Decoding JSON file is File Input /Output (I/O) related operation. The
JSON file must exist on your system at specified the location that you
program.
• Deserialization is the opposite of Serialization, i.e. conversion of JSON objects
into their respective Python objects. The load() method is used for it.
• If you have used JSON data from another program or obtained it as a string
format of JSON, then it can easily be deserialized with load(), which is usually
used to load from a string, otherwise, the root object is in a list or Dict
Example 1 : Python read JSON file
You can use json.load() method to read a file containing JSON object.
Suppose, you have a file named person.json which contains a JSON object.
{"name": "Bob",
"languages": ["English", "French"]
}
Here's how you can parse this file:
import json
with open('path_to_file/person.json', 'r') as f:
data = json.load(f)
print(data)
# Output: {'name': 'Bob', 'languages': ['English', 'French’]}
Here, we have used the open() function to read the json file. Then, the file is parsed using json.load()
method which gives us a dictionary named data.
Example 1 : Python read JSON file
import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
# store file data in object
data = json.load(file_object)
print(data)
Here data is a dictionary object of Python as shown in the above read JSON
file Python example.
Output:
{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
The conversion of JSON data to Python is
based on the following conversion table
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None
.Here translation table show example of JSON objects to Python objects which are helpful to perform
decoding in Python of JSON string
Python to JSON (Encoding)
• we saw how to convert JSON into a Python value (i.e. Dictionary).
• Now, how we can convert (encode) a Python value to JSON? Converting
Python data to JSON is called an Encoding operation. Encoding is done with
the help of JSON library method – dumps()
• Serializing JSON refers to the transformation of data into a series of
bytes (hence serial) to be stored or transmitted across a network.
• To handle the data flow in a file, the JSON library in Python uses dump()
or dumps() function to convert the Python objects into their respective
JSON object, so it makes it easy to write data to files.
So this output is considered the data representation of the object (Dictionary). The method dumps()
was the key to such an operation.
Say that we have the following Dictionary in Python:
The conversion of Python objects to JSON data is based on
the following conversion table.
Python JSON
dict object
List, tuple array
str string
int number (int)
float number (real)
False false
True true
None null
• The keys in a Python dictionary have to be converted to a
string for them to be used as JSON data.
• However, a simple string conversion is only feasible for
basic types like str, int, float, and bool. For other types of
keys, this can result in a TypeError.
• we can avoid that from happening by setting the value of
skipkeys argument to True. This will tell Python to skip all
keys which cannot be converted to a string.
Python Write JSON to File
Method 1: Writing JSON to a file in Python using json.dumps()
We can convert any Python object to a JSON string and write JSON to File
using json.dumps() function and file.write() function respectively.
Following is a step by step process to write JSON to file.
1.Prepare JSON string by converting a Python Object to JSON string using
json.dumps() function.
2.Create a JSON file using open(filename, ‘w’) function. We are opening file
in write mode.
3. simply write JSON string to a file using the “write” function.
4. Close the JSON file.
Example 1: Write JSON (Object) to File
In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file
named data.json.
Python Program
Output
Run the above program, and data.json will be created in the working directory.
Example2
OUTPUT:
Example 3: Write JSON (List of Object) to File
In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file
named data.json.
Python Program
Output
Run the above program, and data.json will be created in the working directory.
data.json
Method 2: Writing JSON to a file in Python using json.dump()
• Another way of writing JSON to a file is by using json.dump() method .
• The JSON package has the “dump” function which directly writes the
dictionary to a file in the form of JSON, without needing to convert it into an
actual JSON object.
It takes 2 parameters:
•dictionary – the name of a dictionary which should be converted to a JSON
object.
•file pointer – pointer of the file opened in write or append mode.
Output:
Format JSON code (Pretty print)
• The aim is to write well-formatted code for human understanding. With the help of
anyone can easily understand the code.
• To analyze and debug JSON data, we may need to print it in a more readable format.
This can be done by passing additional parameters indent and sort_keys to
json.dumps() and json.dump() method.
• sort_keys attribute in Python dumps function’s argument will sort the key in JSON in
ascending order. The sort_keys argument is a Boolean attribute. When it’s true
sorting is allowed otherwise not. Let’s understand with Python string to JSON sorting
example.
In the above program, have used 4 spaces for indentation. And, the keys are sorted in ascending order.
By the way, the default value of indent is None. And, the default value of sort_keys is False.
JSON_FIles-Py (2).pptx
JSON_FIles-Py (2).pptx
To better understand this, change indent to 40 and observe the output-
JSON_FIles-Py (2).pptx
Output:
observe the keys age, cars, children, etc are arranged in
ascending order.
Back and Forth Conversion of Data
• The keys for dictionaries in Python can be of different data types like strings, int, or tuples. However,
the keys in JSON data can only be strings.
• This means that when you convert a dictionary into JSON, all its keys will be cast to strings.
Conversion of this JSON back to a dictionary will not get you back the original data type of the keys.

More Related Content

PPTX
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
DOCX
Json1
thetechbuddyBlog
 
PDF
Dealing with JSON files in python with illustrations
Kiran Kumaraswamy
 
PPTX
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
PPTX
CSV JSON and XML files in Python.pptx
Ramakrishna Reddy Bijjam
 
PPTX
All about XML, JSON and related topics..
tinumanueltmt
 
PPTX
JSON,XML.pptx
Srinivas K
 
PPTX
Json
primeteacher32
 
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
Dealing with JSON files in python with illustrations
Kiran Kumaraswamy
 
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 
CSV JSON and XML files in Python.pptx
Ramakrishna Reddy Bijjam
 
All about XML, JSON and related topics..
tinumanueltmt
 
JSON,XML.pptx
Srinivas K
 

Similar to JSON_FIles-Py (2).pptx (20)

PDF
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
PPTX
JSON-(JavaScript Object Notation)
Skillwise Group
 
PDF
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
PPTX
JSON - (English)
Senior Dev
 
PPTX
LU 1.3. JSON & XML.pptx about how they work and introduction
niyigenagilbert6
 
PPTX
Json
Steve Fort
 
PPTX
JSON.pptx
TilakaRt
 
PPTX
module node jsbhgnbgtyuikmnbvcfyum2.pptx
hemalathas752360
 
PDF
CS8651 IP Unit 2 pdf regulation -2017 anna university
amrashbhanuabdul
 
PPTX
Screaming fast json parsing on Android
Karthik Ramgopal
 
PPT
java script json
chauhankapil
 
PDF
Basics of JSON (JavaScript Object Notation) with examples
Sanjeev Kumar Jaiswal
 
PPT
JSON(JavaScript Object Notation) Presentation transcript
SRI NISHITH
 
PPTX
Files in Python.pptx
Koteswari Kasireddy
 
PPTX
Files in Python.pptx
Koteswari Kasireddy
 
PPTX
Unit-2.pptx
AnujSood25
 
PDF
Json
soumya
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
JSON-(JavaScript Object Notation)
Skillwise Group
 
Json tutorial, a beguiner guide
Rafael Montesinos Muñoz
 
JSON - (English)
Senior Dev
 
LU 1.3. JSON & XML.pptx about how they work and introduction
niyigenagilbert6
 
JSON.pptx
TilakaRt
 
module node jsbhgnbgtyuikmnbvcfyum2.pptx
hemalathas752360
 
CS8651 IP Unit 2 pdf regulation -2017 anna university
amrashbhanuabdul
 
Screaming fast json parsing on Android
Karthik Ramgopal
 
java script json
chauhankapil
 
Basics of JSON (JavaScript Object Notation) with examples
Sanjeev Kumar Jaiswal
 
JSON(JavaScript Object Notation) Presentation transcript
SRI NISHITH
 
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Koteswari Kasireddy
 
Unit-2.pptx
AnujSood25
 
Json
soumya
 
Ad

Recently uploaded (20)

PDF
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
top-5-use-cases-for-splunk-security-analytics.pdf
yaghutialireza
 
Zero Carbon Building Performance standard
BassemOsman1
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
Software Testing Tools - names and explanation
shruti533256
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
Introduction to Data Science: data science process
ShivarkarSandip
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Inventory management chapter in automation and robotics.
atisht0104
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Ad

JSON_FIles-Py (2).pptx

  • 2. What is JSON ? • JSON (JavaScript Object Notation) is a popular data format used for representing structured data. It's common to transmit and receive data between a server and web application in JSON format. • JSON was inspired by the JavaScript programming language, but it's not tied to only one language. • Most modern programming languages have libraries for parsing and generating JSON data.
  • 3. Why do we use JSON ? • JSON has a more compact style than XML which was the format of choice years ago. The light-weight approach can make significant improvements. • The XML software parsing process can take a long time. JSON uses less data overall, so you reduce the cost and increase the parsing speed. • The JSON structure is straight forward and often more readable.
  • 4. Basic JSON syntax • In JSON, data is written in key-value pairs, like so: "first_name": "Katie" • Data is enclosed in double quotation marks and the key-value pair is separated by a colon. • There can be more than one key-value pair and each one is separated by a comma: "first_name": "Katie", "last_name": "Rodgers“ The example above showed an object, a collection of multiple key-value pairs. Objects are inside curly braces: { "first_name": "Katie", "last_name": "Rodgers" }
  • 5. Another example of JSON-formatted data is as follows: { "name": "Frank", "age": 39, "isEmployed": true }
  • 6. We can also create arrays, an ordered list of values, with JSON. In that case, arrays are contained inside square brackets: [ { "first_name": "Katie", "last_name": "Rodgers" }, { "first_name": "Naomi", "last_name": "Green" }, ]
  • 7. // or: { "employee": [ { "first_name": "Katie", "last_name": "Rodgers" }, { "first_name": "Naomi", "last_name": "Green" }, ] } //this created an 'employee' object that has 2 records. // It defines the first name and last name of an employee
  • 8. In Python, JSON exists as a string. For example: p = '{"name": "Bob", "languages": ["Python", "Java"]}' It's also common to store a JSON object in a file.
  • 9. Python and JSON • Python makes it simple to work with JSON files. • Python supports JSON through a built-in package called JSON. • To use this feature, we import the JSON package in Python script. in order to use this module is to import it: import json • This library mainly parses JSON from files or strings. It also parses JSON into a dictionary or list in Python and vice versa, that is converting a Python dictionary or list into JSON strings. • The text in JSON is done through quoted-string which contains the value in key- value mapping within { }. • It is similar to the dictionary in Python.
  • 10. JSON to Python (Decoding) • JSON string decoding is done with the help of method json.loads() & json.load() of JSON library in Python. • Reading JSON means converting JSON into a Python value (object). The json library parses JSON into a dictionary or list in Python.
  • 11. JSON to Python • Example 1: Python JSON to dict • we use the loads() function (load from a string) to parse a JSON string and the method returns a dictionary. Here, jsonData is a JSON string, and jsonToPython is a dictionary.
  • 12. • That is, the data is returned as a Python dictionary (JSON object data structure). • So, the statement print jsonToPython[‘name’] returns ‘Frank’ Note: In the above programs, the objects in JSON are converted to dictionaries in Python.
  • 15. Decoding JSON File or Parsing JSON file in Python(Reading JSON from a file using Python) Let us see how to read JSON file in Python with Python parse JSON example: NOTE: Decoding JSON file is File Input /Output (I/O) related operation. The JSON file must exist on your system at specified the location that you program. • Deserialization is the opposite of Serialization, i.e. conversion of JSON objects into their respective Python objects. The load() method is used for it. • If you have used JSON data from another program or obtained it as a string format of JSON, then it can easily be deserialized with load(), which is usually used to load from a string, otherwise, the root object is in a list or Dict
  • 16. Example 1 : Python read JSON file You can use json.load() method to read a file containing JSON object. Suppose, you have a file named person.json which contains a JSON object. {"name": "Bob", "languages": ["English", "French"] } Here's how you can parse this file: import json with open('path_to_file/person.json', 'r') as f: data = json.load(f) print(data) # Output: {'name': 'Bob', 'languages': ['English', 'French’]} Here, we have used the open() function to read the json file. Then, the file is parsed using json.load() method which gives us a dictionary named data.
  • 17. Example 1 : Python read JSON file import json #File I/O Open function for read data from JSON File with open('X:/json_file.json') as file_object: # store file data in object data = json.load(file_object) print(data) Here data is a dictionary object of Python as shown in the above read JSON file Python example. Output: {'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
  • 18. The conversion of JSON data to Python is based on the following conversion table JSON Python object dict array list string str number (int) int number (real) float true True false False null None .Here translation table show example of JSON objects to Python objects which are helpful to perform decoding in Python of JSON string
  • 19. Python to JSON (Encoding) • we saw how to convert JSON into a Python value (i.e. Dictionary). • Now, how we can convert (encode) a Python value to JSON? Converting Python data to JSON is called an Encoding operation. Encoding is done with the help of JSON library method – dumps() • Serializing JSON refers to the transformation of data into a series of bytes (hence serial) to be stored or transmitted across a network. • To handle the data flow in a file, the JSON library in Python uses dump() or dumps() function to convert the Python objects into their respective JSON object, so it makes it easy to write data to files.
  • 20. So this output is considered the data representation of the object (Dictionary). The method dumps() was the key to such an operation. Say that we have the following Dictionary in Python:
  • 21. The conversion of Python objects to JSON data is based on the following conversion table. Python JSON dict object List, tuple array str string int number (int) float number (real) False false True true None null
  • 22. • The keys in a Python dictionary have to be converted to a string for them to be used as JSON data. • However, a simple string conversion is only feasible for basic types like str, int, float, and bool. For other types of keys, this can result in a TypeError. • we can avoid that from happening by setting the value of skipkeys argument to True. This will tell Python to skip all keys which cannot be converted to a string.
  • 23. Python Write JSON to File
  • 24. Method 1: Writing JSON to a file in Python using json.dumps() We can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively. Following is a step by step process to write JSON to file. 1.Prepare JSON string by converting a Python Object to JSON string using json.dumps() function. 2.Create a JSON file using open(filename, ‘w’) function. We are opening file in write mode. 3. simply write JSON string to a file using the “write” function. 4. Close the JSON file.
  • 25. Example 1: Write JSON (Object) to File In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json. Python Program Output Run the above program, and data.json will be created in the working directory.
  • 27. Example 3: Write JSON (List of Object) to File In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json. Python Program Output Run the above program, and data.json will be created in the working directory. data.json
  • 28. Method 2: Writing JSON to a file in Python using json.dump() • Another way of writing JSON to a file is by using json.dump() method . • The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object. It takes 2 parameters: •dictionary – the name of a dictionary which should be converted to a JSON object. •file pointer – pointer of the file opened in write or append mode.
  • 30. Format JSON code (Pretty print) • The aim is to write well-formatted code for human understanding. With the help of anyone can easily understand the code. • To analyze and debug JSON data, we may need to print it in a more readable format. This can be done by passing additional parameters indent and sort_keys to json.dumps() and json.dump() method. • sort_keys attribute in Python dumps function’s argument will sort the key in JSON in ascending order. The sort_keys argument is a Boolean attribute. When it’s true sorting is allowed otherwise not. Let’s understand with Python string to JSON sorting example.
  • 31. In the above program, have used 4 spaces for indentation. And, the keys are sorted in ascending order. By the way, the default value of indent is None. And, the default value of sort_keys is False.
  • 34. To better understand this, change indent to 40 and observe the output-
  • 36. Output: observe the keys age, cars, children, etc are arranged in ascending order.
  • 37. Back and Forth Conversion of Data • The keys for dictionaries in Python can be of different data types like strings, int, or tuples. However, the keys in JSON data can only be strings. • This means that when you convert a dictionary into JSON, all its keys will be cast to strings. Conversion of this JSON back to a dictionary will not get you back the original data type of the keys.