ANI

10 Python one-liners for Jonson paring and processing

10 Python one-liners for Jonson paring and processing
Photo for Author | Ideogram

Obvious Introduction

Most applications rely heavily on JSON for the data exchange, the configuration management and the contact of API.

The built-in Python module combined with the punctuation and composition of the dictionary makes it possible for us to make the complexity of JSS. These liners contain one of which will help you, change, and issue logical information from JSon Data.

Obvious To create a sample data

Let's make JSON's authentic datasets that represent the common conditions you will meet in the actual petitions of the world:

import json
from collections import defaultdict, Counter

# Sample product catalog
products = [
    {"id": 1, "name": "Laptop", "price": 999.99, "category": "Electronics", "stock": 25, "rating": 4.5},
    {"id": 2, "name": "Coffee Maker", "price": 79.99, "category": "Appliances", "stock": 15, "rating": 4.2},
    {"id": 3, "name": "Smartphone", "price": 699.99, "category": "Electronics", "stock": 50, "rating": 4.7},
    {"id": 4, "name": "Desk Chair", "price": 159.99, "category": "Furniture", "stock": 8, "rating": 4.1},
    {"id": 5, "name": "Headphones", "price": 199.99, "category": "Electronics", "stock": 30, "rating": 4.6}
]

# Sample employee data
employees = [
    {"name": "Alice Johnson", "department": "Engineering", "salary": 95000, "projects": ["API", "Database"]},
    {"name": "Bob Smith", "department": "Marketing", "salary": 65000, "projects": ["Campaign", "Analytics"]},
    {"name": "Carol Davis", "department": "Engineering", "salary": 105000, "projects": ["Frontend", "Testing"]},
    {"name": "David Wilson", "department": "Sales", "salary": 75000, "projects": ["Outreach", "CRM"]}
]

# Sample nested API response
api_response = {
    "status": "success",
    "data": {
        "orders": [
            {"id": "ORD001", "customer": {"name": "John Doe", "email": "[email protected]"}, "items": [{"product": "Laptop", "quantity": 1}]},
            {"id": "ORD002", "customer": {"name": "Jane Smith", "email": "[email protected]"}, "items": [{"product": "Mouse", "quantity": 2}]}
        ],
        "total_orders": 2
    }
}

In the following examples, I left the print statements and focused only on liners themselves.

Obvious 1. To remove all prices with a particular key

When working with JSON Arrays, you often need to take all the prices of some field in all many things. This one liner well puts certain amounts from the structures that rape, making the whole complete list or data preparation for analyzing.

product_names = [item['name'] for item in products]

This list of words tenderly understood each dictionaries in the list of products and issuing the 'name' field. Square Bracket Notation Accessing the key, creating a new list that contains only the required amounts while keeping the actual order.

['Laptop', 'Coffee Maker', 'Smartphone', 'Desk Chair', 'Headphones']

Obvious 2. Sort of JSON's items in form

Data filtering is important when working with the Great Data for JSS. This One-Liner includes a comprehensive comprehension of comprehension information only for specific issues, enables instantaneous data of immediate data without complex loops.

expensive_products = [item for item in products if item['price'] > 200]

The conditional condition assesses each product's price and only including those things in which the condition is true.

[{'id': 1,
  'name': 'Laptop',
  'price': 999.99,
  'category': 'Electronics',
  'stock': 25,
  'rating': 4.5},
 {'id': 3,
  'name': 'Smartphone',
  'price': 699.99,
  'category': 'Electronics',
  'stock': 50,
  'rating': 4.7}]

Obvious 3. Planning JSON's items with a field of field

Data to distinguish data by specific symptoms is a common need for data processing. The One-Liner creates a dictionary where the keys representing different fields and heritage prices containing a list of responsibilities, enabling the applicable data organization and analysis.

products_by_category = {k: [item for item in products if item['category'] == k] for k in set(item['category'] for item in products)}

The dictionary of the dictionary begins creating a set of unique class values, and in each category, filtering a list of products only to include the same items.

{'Furniture': [{'id': 4,
   'name': 'Desk Chair',
   'price': 159.99,
   'category': 'Furniture',
   'stock': 8,
   'rating': 4.1}],
 'Appliances': [{'id': 2,
   'name': 'Coffee Maker',
   'price': 79.99,
   'category': 'Appliances',
   'stock': 15,
   'rating': 4.2}],
 'Electronics': [{'id': 1,
   'name': 'Laptop',
   'price': 999.99,
   'category': 'Electronics',
   'stock': 25,
   'rating': 4.5},
  {'id': 3,
   'name': 'Smartphone',
   'price': 699.99,
   'category': 'Electronics',
   'stock': 50,
   'rating': 4.7},
  {'id': 5,
   'name': 'Headphones',
   'price': 199.99,
   'category': 'Electronics',
   'stock': 30,
   'rating': 4.6}]}

Obvious 4. Consolidated statistics from JSON

The fast-speed analysis of JSON data helps identify styles and patterns. This one liner includes many combined activities at the same time, provides comprehensive details of your data signs without writing statistics.

price_stats = {'min': min(item['price'] for item in products), 'max': max(item['price'] for item in products), 'avg': sum(item['price'] for item in products) / len(products)}

The dictionary is valid for different components compiled at certain amounts issued, using Generator speeches.

{'min': 79.99, 'max': 999.99, 'avg': 427.98999999999995}

Obvious 5. Turning the form of JSON

Renovating JSON's data to match different schemas or API requirements are often required. This one liner creates new items in modified field names, rated prices, or filtered attributes, which enables the conversion of the seaman data between different program formats between different program formats.

simplified_products = [{'title': item['name'], 'cost': item['price'], 'available': item['stock'] > 0} for item in products]

The understanding of the list creates new dictionaries with converted field names and boolean prices. This method allows the renaming of the field, type the conversion, and the qualifications included in one speech while storing clean, readable code.

[{'title': 'Laptop', 'cost': 999.99, 'available': True},
 {'title': 'Coffee Maker', 'cost': 79.99, 'available': True},
 {'title': 'Smartphone', 'cost': 699.99, 'available': True},
 {'title': 'Desk Chair', 'cost': 159.99, 'available': True},
 {'title': 'Headphones', 'cost': 199.99, 'available': True}]

Obvious 6. To remove the purposes of the purposes of safety

Nestd Json Data requires carefully dealing with any keys that are not avoiding errors. This One-Liner uses how to find automatic prices safeguard security information prescribed, verify the strong code that can also be incomplete or unapproved data.

customer_emails = [order.get('customer', {}).get('email', 'N/A') for order in api_response['data']['orders']]

Imprisonment .get() Ways provide default prices for each level, to prevent KeyErrordifferent when you reach organized structures. This method is important when it works with external apis or user-made data where the existence of the field is guaranteed.

Obvious 7. Counting what happened in field prices

Understanding the data distribution patterns requires calculation that certain specified amounts appear in your data. This one liner creates a field price map in the field, providing immediate discretion of data composition and helping to see regular patterns or merchants.

category_counts = Counter(item['category'] for item in products)

This page Counter Class adds automatically to the occurrence of each unique value from the genital expression. This method works more efficiently than manual loops.

Counter({'Electronics': 3, 'Appliances': 1, 'Furniture': 1})

Obvious 8. Matching many JSON Things

Integrating data from many JSS sources is common when working with microsavices or combined systems. This one liner includes items with comparative keys, creating integrated records contain information from different sources.

enhanced_products = [{**product, 'total_value': product['price'] * product['stock']} for product in products]

The dictionary to unlock the existing fields while adding new combined prices.



[{'id': 1,
  'name': 'Laptop',
  'price': 999.99,
  'category': 'Electronics',
  'stock': 25,
  'rating': 4.5,
  'total_value': 24999.75},
 {'id': 2,
  'name': 'Coffee Maker',
  'price': 79.99,
  'category': 'Appliances',
  'stock': 15,
  'rating': 4.2,
  'total_value': 1199.85},
...
 {'id': 5,
  'name': 'Headphones',
  'price': 199.99,
  'category': 'Electronics',
  'stock': 30,
  'rating': 4.6,
  'total_value': 5999.700000000001}]

Obvious 9. Finding high-quality / smaller price items

Records identify the records of the worst prices is important for data analysis and quality control. This One-Liner receives the highest or low prices in specific fields, enables immediate identification for retailers, top players, or edge charges in your data.

highest_rated = max(products, key=lambda x: x['rating'])

This page max work with key Parameter returns something with the key value of the Max this keyword. This method is more readable than the Itemation manually and works with any compatible field, including wires and days.

{'id': 3,
 'name': 'Smartphone',
 'price': 699.99,
 'category': 'Electronics',
 'stock': 50,
 'rating': 4.7}

Obvious 10

JSON's complex properties usually contain organized arrays need to be taken with analysis or processing. This one single release also includes materials from the specified list, creates one simple structure that is easy to work in the next function.

projects_list = [project for employee in employees for project in employee['projects']]

Understanded List of Listing List of Human Resources, then in a list of each work projects, creates soft words in all the project names. This double Loop structure deals with a variety of arrays.

['API',
 'Database',
 'Campaign',
 'Analytics',
 'Frontend',
 'Testing',
 'Outreach',
 'CRM']

Obvious Store

These Python One-liners show how Python is helpful to deceive JSON data.

The key is understanding of the built-in function within the Python, understanding, and a flexibility of dictionary.

Using these, you will be able to process the API answers immediately, change the data between different formats, and issue useful details from the JSON's complex information.

Count Priya c He is the writer and a technical writer from India. He likes to work in mathematical communication, data science and content creation. His areas of interest and professionals includes deliefs, data science and natural language. She enjoys reading, writing, coding, and coffee! Currently, he works by reading and sharing his knowledge and engineering society by disciples of teaching, how they guide, pieces of ideas, and more. Calculate and create views of the resources and instruction of codes.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button