杰瑞科技汇

python json concat

Of course! The term "JSON concat" can mean a few different things. I'll cover the most common interpretations, from simple string concatenation to merging JSON objects and arrays.

python json concat-图1
(图片来源网络,侵删)

Summary: What Do You Mean by "Concat"?

  1. Concatenate JSON Strings? You have two strings that are valid JSON and you want to join them into one string. (Simple string joining).
  2. Merge/Concatenate JSON Objects? You have two or more JSON objects and you want to combine them into a single object, adding their key-value pairs together. (This is what people usually mean).
  3. Concatenate JSON Arrays? You have two or more JSON arrays and you want to combine them into a single array, adding their elements together.

Let's go through each with clear examples.


Concatenating JSON Strings (Simple String Joining)

If you literally have two strings and you just want to join them with a separator, you can use Python's standard string methods.

Scenario: You have two JSON strings in a file or from an API and want to combine them into a single string.

json_str1 = '{"name": "Alice", "age": 30}'
json_str2 = '{"city": "New York", "job": "Engineer"}'
separator = ", "
# Simply join the strings
concatenated_string = json_str1 + separator + json_str2
print(concatenated_string)
# Output: {"name": "Alice", "age": 30}, {"city": "New York", "job": "Engineer"}

⚠️ Important Note: The result is NOT a valid JSON object. It's just a string. You cannot parse this result directly with json.loads().

python json concat-图2
(图片来源网络,侵删)

Merging/Combining JSON Objects (Most Common Use Case)

This is the most frequent requirement. You have two dictionaries (Python's equivalent of JSON objects) and you want to merge them. If a key exists in both, you need a strategy to handle the conflict (e.g., overwrite, raise an error, or combine nested objects).

Method A: Using the Dictionary Unpacking Operator () - Python 3.5+

This is the most modern, readable, and recommended way.

import json
# Python dictionaries represent JSON objects
json_obj1 = {"name": "Alice", "age": 30}
json_obj2 = {"city": "New York", "job": "Engineer"}
# The second dictionary's values will overwrite the first's in case of a conflict
merged_obj = {**json_obj1, **json_obj2}
print(merged_obj)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
# To get the final JSON string
json_string = json.dumps(merged_obj, indent=2)
print(json_string)

Method B: Using the Union Operator - Python 3.9+

This is an even cleaner syntax introduced in Python 3.9.

import json
json_obj1 = {"name": "Alice", "age": 30}
json_obj2 = {"city": "New York", "job": "Engineer"}
# The second dictionary's values overwrite the first's
merged_obj = json_obj1 | json_obj2
print(merged_obj)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}

Method C: Handling Conflicts Deeply (Merging Nested Objects)

What if you have nested objects and you want to merge them instead of overwriting? This requires a custom function.

import json
def deep_merge(dict1, dict2):
    """Merges dict2 into dict1. Handles nested dictionaries."""
    merged = dict1.copy()  # Start with dict1's keys and values
    for key, value in dict2.items():
        if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
            # If the key exists in both and both values are dicts, merge them recursively
            merged[key] = deep_merge(merged[key], value)
        else:
            # Otherwise, just overwrite the key with the value from dict2
            merged[key] = value
    return merged
json_obj1 = {
    "name": "Alice",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Boston"
    }
}
json_obj2 = {
    "job": "Engineer",
    "address": {
        "city": "New York", # This will overwrite the city in obj1
        "zip": "10001"     # This will be added to the address
    }
}
deeply_merged_obj = deep_merge(json_obj1, json_obj2)
print(json.dumps(deeply_merged_obj, indent=2))

Output:

{
  "name": "Alice",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "zip": "10001"
  },
  "job": "Engineer"
}

Concatenating JSON Arrays

This means combining two lists into one larger list.

Method A: Using the Operator

This is the simplest and most direct way to concatenate two lists.

import json
# Python lists represent JSON arrays
json_array1 = [1, 2, 3]
json_array2 = [4, 5, 6]
# Combine the lists
concatenated_array = json_array1 + json_array2
print(concatenated_array)
# Output: [1, 2, 3, 4, 5, 6]
# To get the final JSON string
json_string = json.dumps(concatenated_array)
print(json_string)
# Output: [1, 2, 3, 4, 5, 6]

Method B: Using the extend() Method

This method modifies the first list in-place instead of creating a new one.

import json
json_array1 = [1, 2, 3]
json_array2 = [4, 5, 6]
json_array1.extend(json_array2)
print(json_array1)
# Output: [1, 2, 3, 4, 5, 6]

Method C: Concatenating a List of Arrays

If you have a list of arrays and want to combine them all, itertools.chain.from_iterable is very efficient.

import json
from itertools import chain
list_of_arrays = [[1, 2], [3, 4], [5]]
# chain.from_iterable flattens the list of lists
concatenated_array = list(chain.from_iterable(list_of_arrays))
print(concatenated_array)
# Output: [1, 2, 3, 4, 5]

Full Workflow Example: Reading, Merging, and Writing JSON

Let's put it all together. Imagine you have two JSON files, data1.json and data2.json.

data1.json

{
  "id": 101,
  "user": "charlie",
  "settings": {
    "theme": "dark",
    "notifications": true
  }
}

data2.json

{
  "id": 102,
  "user": "dave",
  "settings": {
    "language": "en-US",
    "notifications": false
  }
}

merge_script.py

import json
def deep_merge(dict1, dict2):
    """Merges dict2 into dict1. Handles nested dictionaries."""
    merged = dict1.copy()
    for key, value in dict2.items():
        if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
            merged[key] = deep_merge(merged[key], value)
        else:
            merged[key] = value
    return merged
# 1. Load the JSON data from files
with open('data1.json', 'r') as f1:
    data1 = json.load(f1)
with open('data2.json', 'r') as f2:
    data2 = json.load(f2)
# 2. Merge the two dictionaries
# Note: This simple merge will overwrite the 'id' and 'user' from data1 with data2.
# A more complex script might handle these as list items.
# For this example, we'll assume data2 is meant to update data1.
merged_data = deep_merge(data1, data2)
# 3. Write the merged data to a new file
with open('merged_data.json', 'w') as f_out:
    json.dump(merged_data, f_out, indent=2)
print("Merged data saved to merged_data.json")

merged_data.json (Output)

{
  "id": 102,
  "user": "dave",
  "settings": {
    "theme": "dark",
    "notifications": false,
    "language": "en-US"
  }
}
分享:
扫描分享到社交APP
上一篇
下一篇