【Python 学习笔记】json

How does python work with json?

1. Loading JSON Data

If you have JSON data as a string or in a file, you can load it into a Python dictionary (or list, if the JSON data is an array) using json.loads() (for strings) or json.load() (for files).

python 复制代码
import json

# From a JSON string
json_data = '{"name": "Alice", "age": 25, "city": "New York"}'
data = json.loads(json_data)
print(data)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

# From a JSON file
with open('data.json') as file:
    data = json.load(file)
    print(data)

To convert a Python dictionary (or other JSON-serializable Python objects) into a JSON string, you can use json.dumps(). For writing to a file, use json.dump().

python 复制代码
# Convert Python dict to JSON string
python_data = {"name": "Alice", "age": 25, "city": "New York"}
json_string = json.dumps(python_data)
print(json_string)  # Output: {"name": "Alice", "age": 25, "city": "New York"}

# Write to a JSON file
with open('output.json', 'w') as file:
    json.dump(python_data, file)

3. Handling Nested JSON

If the JSON data has nested objects, you can access them by chaining dictionary keys or list indices.

python 复制代码
nested_json = '{"person": {"name": "Alice", "age": 25}, "city": "New York"}'
data = json.loads(nested_json)
print(data['person']['name'])  # Output: Alice

4. Formatting Options

json.dumps() has optional parameters for pretty-printing, sorting keys, and customizing output format.

python 复制代码
# Pretty-print JSON
formatted_json = json.dumps(python_data, indent=4, sort_keys=True)
print(formatted_json)

Why Use sort_keys?

  • Readability: It makes it easier to locate keys in large JSON outputs.
  • Consistency: Sorted keys provide consistent output, which is useful when comparing JSON strings.
  • Debugging: Having a predictable order can simplify debugging by avoiding unnecessary differences due to key ordering.

example for JSON data is an array?

Certainly! JSON data can be structured as an array, where the top-level element is a list (array) of JSON objects, rather than a single JSON object. This is common when representing collections of data, like a list of users, products, or other similar records.

python 复制代码
[
    {
        "id": 1,
        "name": "Alice",
        "age": 25,
        "city": "New York"
    },
    {
        "id": 2,
        "name": "Bob",
        "age": 30,
        "city": "Chicago"
    },
    {
        "id": 3,
        "name": "Charlie",
        "age": 35,
        "city": "San Francisco"
    }
]

How to Work with JSON Arrays in Python

You can load this JSON array into Python and iterate over the list of dictionaries

python 复制代码
import json

# JSON array as a string
json_array = '''
[
    {"id": 1, "name": "Alice", "age": 25, "city": "New York"},
    {"id": 2, "name": "Bob", "age": 30, "city": "Chicago"},
    {"id": 3, "name": "Charlie", "age": 35, "city": "San Francisco"}
]
'''

# Parse JSON array into Python list
data = json.loads(json_array)

# Accessing elements
for person in data:
    print(f"Name: {person['name']}, Age: {person['age']}, City: {person['city']}")
python 复制代码
Name: Alice, Age: 25, City: New York
Name: Bob, Age: 30, City: Chicago
Name: Charlie, Age: 35, City: San Francisco

Key Points

  • JSON arrays are loaded as Python lists.
  • Each item in the array is typically a JSON object (dictionary in Python).
  • You can iterate through the list and access each dictionary by its keys.

how do you load this json_array to a table?

python 复制代码
import json
import pandas as pd

# JSON array as a string
json_array = '''
[
    {"id": 1, "name": "Alice", "age": 25, "city": "New York"},
    {"id": 2, "name": "Bob", "age": 30, "city": "Chicago"},
    {"id": 3, "name": "Charlie", "age": 35, "city": "San Francisco"}
]
'''

# Load JSON data from file
with open('data.json') as file:
    data = json.load(file)

# Parse JSON array into a Python list
data = json.loads(json_array)
python 复制代码
   id     name  age           city
0   1    Alice   25       New York
1   2      Bob   30        Chicago
2   3  Charlie   35  San Francisco

Summary

  • Use json.loads() to parse a JSON array from a string or json.load() from a file.
  • Convert the parsed JSON data to a DataFrame using pd.DataFrame(data).
  • Each JSON object in the array becomes a row in the DataFrame.

"Answer Generated by OpenAI's ChatGPT"

相关推荐
CSDN_PBB3 小时前
[STM32 - 野火] - - - 固件库学习笔记 - - - 十五.设置FLASH的读写保护及解除
笔记·stm32·学习
鸡啄米的时光机7 小时前
vscode的一些实用操作
vscode·学习
Kai HVZ7 小时前
《深度学习》——调整学习率和保存使用最优模型
人工智能·深度学习·学习
守护者1708 小时前
JAVA学习-练习试用Java实现“使用Apache Ignite对大数据进行内存计算和快速筛查”
java·学习
夜流冰8 小时前
编程参考 - C语言可变参数
笔记
格雷亚赛克斯9 小时前
Qt笔记31-69
数据库·笔记·qt
Long_poem9 小时前
【自学笔记】版本控制与持续集成基础知识点总览-持续更新
笔记·ci/cd
Stream٩( 'ω' )و9 小时前
109~133笔记
笔记
weixin_5025398510 小时前
rust学习笔记2-rust的包管理工具Cargo使用
笔记·学习·rust
孤独得猿11 小时前
排序算法复习——包括插入排序、希尔排序、冒泡排序、快排(包括霍尔法、挖坑法、快慢指针法)、堆排、选择排序、归并排序等 (代码采用c/c++混编)
c语言·数据结构·c++·笔记·算法·排序算法