为什么执行完这个json文件合并,就显示个没完没了json的内容?


# 为什么执行完这个json文件合并,就显示个没完没了json的内容?

import os
import json
from datetime import datetime

def merge_filtered_JSON_files(directory_path, output_path):
    merged_data = []
    processed_files = 0

    # Traverse through files in the directory
    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)

        # Filter out JSON files larger than 700MB
        if os.path.isfile(file_path) and filename.endswith('.json') and \
           os.path.getsize(file_path) <= 700 * 1024 * 1024:

            # Check for duplicate filenames
            name, extension = os.path.splitext(filename)
            new_filename = filename
            timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
            counter = 1

            while new_filename in [item.get('filename', '') for item in merged_data]:
                new_filename = f"{name}_{counter}_{timestamp}{extension}"
                counter += 1

            # Open and read the JSON file
            with open(file_path, 'r') as file:
                data = json.load(file)

                # Add data to the merged list (deduplicate)
                if data not in merged_data:
                    data['filename'] = new_filename
                    merged_data.append(data)

            processed_files += 1
            print(f"Processed {processed_files} files")

    # Save the merged data as a JSON file
    with open(output_path, 'w') as output_file:
        json.dump(merged_data, output_file, indent=4)

def recursive_print_data(data):
    if isinstance(data, dict):
        for key, value in data.items():
            print(f"{key}: {value}")
            recursive_print_data(value)
    elif isinstance(data, list):
        for item in data:
            recursive_print_data(item)

def save_text_file(data, output_path):
    with open(output_path, 'w') as file:
        if isinstance(data, dict):
            for key, value in data.items():
                file.write(f"Question: {key}\n")
                file.write(f"Answer: {value}\n\n")
        elif isinstance(data, list):
            for item in data:
                question = item.get('question', '')
                answer = item.get('answer', '')
                file.write(f"Question: {question}\n")
                file.write(f"Answer: {answer}\n\n")
        else:
            file.write(f"{data}\n")

# 目录路径和输出路径
directory_path = '/path/to/your/directory'
output_json_path = '/path/to/your/output.json'
output_txt_path = '/path/to/your/output.txt'

# 合并过滤后的 JSON 文件
merge_filtered_JSON_files(directory_path, output_json_path)

# 打开保存的 JSON 文件并列出基本信息
with open(output_json_path, 'r') as file:
    merged_data = json.load(file)

recursive_print_data(merged_data)

# 将对话或问答形式保存为文本文件
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
output_txt_path_with_timestamp = f"{output_txt_path}_{timestamp}"
save_text_file(merged_data, output_txt_path_with_timestamp)

问题点: 数据合并后,一直打印信息.
分析: recursive_print_data 这个函数执行输出打印功能.
recursive_print_data 本身还自我嵌套
解决办法: 注释掉第76行的代码,让recursive_print_data函数不要执行.

  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7632189
  • 这篇博客也不错, 你可以看下把后端返回的json数据格式化显示在页面上,类似json.cn
  • 除此之外, 这篇博客: 微信小程序项目中JSON文件的作用详解中的 页面的json配置文件: 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 小程序的每一个页面中,可以使用当前页面的json文件来对当前页面的外观窗口样式来进行配置,页面中的配置会覆盖app.json中对当前页面的全局配置项。 

     

     

  • 您还可以看一下 刘高联老师的亲自动手写一个深度学习框架课程中的 代码实践:利用json定义网络结构小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    在执行合并json文件操作后,出现输出结果持续不断重复的情况,可能是由于以下原因导致:

    1. 代码逻辑错误:在合并json文件的过程中,可能存在重复的逻辑操作或循环操作,导致结果重复输出。
    2. 数据重复:合并json文件时,输入的文件中可能存在重复的数据,导致输出结果也会重复。

    为了解决这个问题,可以进行以下步骤:

    步骤1: 检查代码逻辑 首先,需要仔细检查合并json文件的代码逻辑,确保没有重复的操作或循环。可以使用debug工具来逐步执行代码并观察输出结果,找出导致结果重复的原因。如果发现重复的操作,可以将其删除或修正。

    步骤2: 数据去重 如果代码逻辑没有问题,则可能是由于输入文件中存在重复数据导致输出结果重复。可以使用以下步骤对数据进行去重:

    1. 读取输入文件中的json数据。
    2. 使用一个集合(set)来存储已经处理过的数据,确保数据的唯一性。
    3. 遍历每个json对象,将其转换为字符串。
    4. 判断该字符串是否已经存在于集合中。
    5. 如果存在,说明该数据已经处理过,跳过处理。
    6. 如果不存在,将该字符串添加到集合中,并将该数据写入输出文件。
    7. 最后,输出的结果将不再重复。

    具体的代码示例如下:

    import json
    
    def merge_json(input_files, output_file):
        processed_data = set()  # 存储已经处理过的数据
    
        with open(output_file, 'w') as outfile:
            for input_file in input_files:
                with open(input_file) as infile:
                    data = json.load(infile)
                    for item in data:
                        item_str = json.dumps(item, sort_keys=True)  # 将json对象转换为字符串
                        if item_str not in processed_data:
                            outfile.write(json.dumps(item) + '\n')
                            processed_data.add(item_str)  # 将处理过的数据添加到集合中
    
    # 调用示例
    input_files = ['data1.json', 'data2.json']  # 输入的json文件列表
    output_file = 'merged_data.json'  # 输出的合并后的json文件
    merge_json(input_files, output_file)
    

    将上述代码中的input_filesoutput_file替换为实际的文件路径,即可合并json文件并去除重复数据。

    希望以上解决方案能够帮助你解决问题,如果仍然存在困惑或其他问题,请随时追问。

recursive_print_data(merged_data)
不是你自己写的,打印所有的内容吗