Python: converting a list of dictionaries to json

Python: converting a list of dictionaries to json

You can convert a list of dictionaries to JSON format in Python using the json module's json.dumps() function. Here's how you can do it:

import json # List of dictionaries data = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 22} ] # Convert to JSON format json_data = json.dumps(data, indent=4) # Print the JSON data print(json_data) 

In this example, the json.dumps() function is used to convert the list of dictionaries data into a JSON-formatted string. The indent parameter is used to specify the number of spaces for indentation to make the JSON output more readable.

The resulting JSON output will look like this:

[ { "name": "Alice", "age": 25 }, { "name": "Bob", "age": 30 }, { "name": "Charlie", "age": 22 } ] 

This JSON-formatted string can be saved to a file, sent over a network, or used in any other context where JSON data is needed.

Examples

  1. Query: "How to convert a list of dictionaries to JSON in Python?"

    • Description: Convert a list of dictionaries to a JSON-formatted string using the json module.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] json_string = json.dumps(data) print(json_string) 
  2. Query: "Convert a list of dictionaries to JSON file in Python"

    • Description: Write a list of dictionaries to a JSON file using the json.dump method.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] with open("output.json", "w") as file: json.dump(data, file) 
  3. Query: "Python pretty-print JSON from list of dictionaries"

    • Description: Convert a list of dictionaries to a JSON-formatted string with pretty-printing for better readability.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] pretty_json = json.dumps(data, indent=4) print(pretty_json) 
  4. Query: "Python convert list of dictionaries to JSON with custom sort order"

    • Description: Convert a list of dictionaries to a JSON-formatted string with a custom key sorting.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] sorted_json = json.dumps(data, sort_keys=True) print(sorted_json) 
  5. Query: "Python check if list of dictionaries is valid JSON"

    • Description: Verify if a given list of dictionaries can be converted to valid JSON.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] try: json.dumps(data) print("Valid JSON") except (TypeError, OverflowError): print("Invalid JSON") 
  6. Query: "Python convert list of dictionaries to JSON and back"

    • Description: Convert a list of dictionaries to JSON and then back to a list of dictionaries to verify data integrity.
    • Code:
      import json data = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25} ] json_string = json.dumps(data) new_data = json.loads(json_string) print(new_data) 
  7. Query: "Python convert list of complex dictionaries to JSON"

    • Description: Handle more complex dictionaries, including nested dictionaries and lists.
    • Code:
      import json data = [ { "name": "Alice", "age": 30, "address": {"street": "123 Main St", "city": "Springfield"}, "hobbies": ["reading", "coding"] }, { "name": "Bob", "age": 25, "address": {"street": "456 Elm St", "city": "Shelbyville"}, "hobbies": ["gaming", "painting"] } ] json_string = json.dumps(data, indent=4) print(json_string) 
  8. Query: "Python convert list of dictionaries with datetime to JSON"

    • Description: Convert a list of dictionaries to JSON while handling datetime objects.
    • Code:
      import json from datetime import datetime def datetime_serializer(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError("Type not serializable") data = [ {"name": "Alice", "age": 30, "birthdate": datetime(1991, 7, 20)}, {"name": "Bob", "age": 25, "birthdate": datetime(1996, 5, 14)} ] json_string = json.dumps(data, default=datetime_serializer, indent=4) print(json_string) 
  9. Query: "Python convert list of dictionaries with None values to JSON"

    • Description: Convert a list of dictionaries to JSON and ensure None values are handled properly.
    • Code:
      import json data = [ {"name": "Alice", "age": 30, "address": None}, {"name": "Bob", "age": 25, "address": None} ] json_string = json.dumps(data, indent=4) print(json_string) 
  10. Query: "Python convert list of dictionaries to JSON with byte data"


More Tags

ubuntu-14.04 azure-active-directory vertical-scrolling belongs-to dead-reckoning task fibonacci momentjs dependency-injection topshelf

More Python Questions

More Retirement Calculators

More Genetics Calculators

More Statistics Calculators

More Physical chemistry Calculators