Hướng dẫn python merge json files - python hợp nhất tệp json

Giả sử có 3 tệp - data1.json, data2.json, data3.json.

Nội phân Chính showShow

  • David Emmanuel công chứng đạo đức
  • Những người khác cũng xem
  • Khám phá các chủ đề
  • Làm thế nào để bạn hợp nhất các tệp JSON trong Python?
  • Làm cách nào để kết hợp các tệp JSON?
  • Làm cách nào để tải nhiều tệp JSON trong Python?
  • JSON Dump Python là gì?

Hãy nói Data1.json chứa -

{ 
   "Players":[ 
      { 
         "name":"Alexis Sanchez",
         "club":"Manchester United"
      },
      { 
         "name":"Robin van Persie",
         "club":"Feyenoord"
      }
   ]
}

Data2.json chứa -

{ 
   "Players":[ 
      { 
         "name":"Nicolas Pepe",
         "club":"Arsenal"
      }
   ]
}

Data3.json chứa -

{ 
   "players":[ 
      { 
         "name":"Gonzalo Higuain",
         "club":"Napoli"
      },
      { 
         "name":"Sunil Chettri",
         "club":"Bengaluru FC"
      }
   ]
}

Việc hợp nhất 3 tệp này sẽ tạo một tệp với dữ liệu sau. result.json -

{ 
   "players":[ 
      { 
         "name":"Alexis Sanchez",
         "club":"Manchester United"
      },
      { 
         "name":"Robin van Persie",
         "club":"Feyenoord"
      },
      { 
         "name":"Nicolas Pepe",
         "club":"Arsenal"
      },
      { 
         "name":"Gonzalo Higuain",
         "club":"Napoli"
      },
      { 
         "name":"Sunil Chettri",
         "club":"Bengaluru FC"
      }
   ]
}

Làm thế nào để mở nhiều tệp JSON từ thư mục và hợp nhất chúng trong tệp JSON đơn trong Python?

Cách tiếp cận của tôi:

import os, json
import pandas as pd
path_to_json =  #path for all the files.
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

jsons_data = pd.DataFrame(columns=['name', 'club'])

for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)

        name = json_text['strikers'][0]['name']
        club = json_text['strikers'][0]['club']

        jsons_data.loc[index] = [name, club]

print(jsons_data)

Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây. Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn. Tìm hiểu thêm về các ký tự unicode hai chiều

# Bạn có tệp File1.json và File2.json.
# Mỗi tệp có cấu trúc:
# [{"key1": "value1"}] - (trong file1)
# [{"key2": "value2"}] - (trong file2)
# Và mục tiêu của bạn là hợp nhất chúng và xem tiếp theo:
# [{"key1": "value1"},
# {"key2": "value2"}]]
Nhập khẩu json
Nhập khẩu glob
result = [] = []
forfinglob.glob ("*. json"): f in glob.glob("*.json"):
withopen (f, "rb") asinfile: open(f, "rb") as infile:
result.append (json.load (infile)).append(json.load(infile))
withopen ("serged_file.json", "wb") asoutfile: open("merged_file.json", "wb") as outfile:
json.dump (kết quả, trang phục, thụt lề = 4).dump(result, outfile, indent=4)

David Emmanuel công chứng đạo đức

David Emmanuel công chứng đạo đức

Xuất bản ngày 1 tháng 12 năm 2021

Xin chào, tôi muốn chỉ ra rằng mọi phản hồi đều được chào đón nhiều hơn, tôi đã tạo ra giải pháp này vì tôi không thể tìm thấy nó ở bất cứ đâu, tập lệnh nhỏ này đọc một danh sách các tệp dựa trên tên tệp chẳng hạn: ví dụ:

Hãy nói rằng bạn có một cái gì đó như thế này:

09/03/2018 07:01 p. m.              173 file-20180309T200145.json
09/03/2018 11:01 p. m.              173 file-20180310T000129.json
10/03/2018 03:01 a. m.              173 file-20180310T040117.json
10/03/2018 07:01 a. m.              173 file-20180310T080111.json
10/03/2018 11:01 a. m.              173 file-20180310T120127.json
11/03/2018 03:01 p. m.              173 file-20180311T160118.json

Và bạn cần hợp nhất chúng càng nhanh càng tốt trước khi nhập, đây là khi tập lệnh này trở nên tiện dụng, vì nó cũng thêm tên tệp vào dữ liệu và bạn có thể theo dõi dữ liệu thô của mình.

Assumptions:

  1. Tập lệnh Python phải nằm trong cùng thư mục với các tệp JSON.same directory as the json files.
  2. Tập lệnh Python và các tệp khác Whitin cùng một thư mục phải có tên khác với các tệp được hợp nhấtMUST have a different name than the files to be merged

Mật mã:

import os
import glob
import json
import pandas as pd
import numpy as np
import csv
from findtools.find_files import (find_files, Match)
from pandas.io.json import json_normalize


cwd = os.getcwd()
path_to_json =cwd


#contents = []
File_prefix = 'file-*'


dfs = []


# Recursively find all *.json files in **/home/**
json_files_pattern = Match(filetype='f', name=File_prefix)
found_files = find_files(path='.', match=json_files_pattern)


for found_file in found_files:
		#-----------------------------------------------------
		f = open(found_file)
		data ​= json.load(f)
		f.close()


		df = pd.DataFrame.from_dict(data, orient='columns')
		##set the json to a pandas dataframe in a table form to a csv
		
		
		df = pd.DataFrame.from_dict(data, orient='columns')
		df['filename'] = pd.Series(found_file)
		dfs.append(df) # append the data frame to the list
		#add the filename column
	
		#------------------------------------------------------
		print ("Adding... "  + found_file)
temp = pd.concat(dfs, ignore_index=True) #to add multiple jsons
print ("Saving ...."  + File_prefix + " File")
temp.to_csv("data"+ "File_prefix" + ".csv")

Hãy chia sẻ phản hồi của bạn và cảm ơn bạn.

Những người khác cũng xem

Khám phá các chủ đề

Làm thế nào để bạn hợp nhất các tệp JSON trong Python?

Làm cách nào để kết hợp các tệp JSON?.

Làm cách nào để tải nhiều tệp JSON trong Python?

JSON Dump Python là gì?

Hãy nói Data1.json chứa -

data.append(json.load(infile)).

Data2.json chứa -

Data3.json chứa -

Việc hợp nhất 3 tệp này sẽ tạo một tệp với dữ liệu sau. result.json -

Làm cách nào để kết hợp các tệp JSON?

Làm cách nào để tải nhiều tệp JSON trong Python?

Làm cách nào để tải nhiều tệp JSON trong Python?

JSON Dump Python là gì?.

Hãy nói Data1.json chứa -

Data2.json chứa -

Data3.json chứa -

Việc hợp nhất 3 tệp này sẽ tạo một tệp với dữ liệu sau. result.json -

JSON Dump Python là gì?

Hãy nói Data1.json chứa -used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.