如何用Pandas将grant_id设为索引输出指定格式的JSON?
grant_id as the Key in Pandas JSON Output Instead of Default Numeric Indices The issue with your current code is that you're structuring the DataFrame incorrectly, which leads to those unwanted numeric indices in your JSON output. Let's fix this with two straightforward approaches—one tailored for your existing Pandas workflow, and a simpler alternative if you don't need full DataFrame functionality.
Approach 1: Adjust Your Pandas Code
Here's how to rework your code to use grant_id as the top-level key in your JSON:
import pandas as pd # Assume grant_ids and patent_title are your existing lists dataDict = { 'grant_id': list(grant_ids), 'patent_title': list(patent_title) } # Create a standard column-based DataFrame first df = pd.DataFrame(dataDict) # Set grant_id as the DataFrame's index (this becomes our JSON key) df.set_index('grant_id', inplace=True) # Export to JSON with orient='index' to use the index values as top-level keys df.to_json('output_json.json', orient='index')
Why this works:
- Your original code used
orient='index'when creating the DataFrame, which flipped the structure (treatinggrant_id/patent_titleas rows instead of columns). By first building a standard column-based DataFrame, then settinggrant_idas the index, we ensure the JSON uses those IDs as keys. - The
orient='index'parameter into_json()tells Pandas to use the DataFrame's index values as the top-level keys in the final JSON.
Approach 2: Direct Dictionary Construction (No Pandas Needed)
If you only need to generate this specific JSON structure and don't require Pandas for other processing, this method is more lightweight:
import json # Build the target dictionary directly by pairing grant IDs with titles result_dict = {grant_id: {"patent_title": title} for grant_id, title in zip(grant_ids, patent_title)} # Write to JSON file (add indent=4 for readable formatting, optional) with open('output_json.json', 'w') as f: json.dump(result_dict, f, indent=4)
This skips Pandas entirely and constructs the exact JSON structure you want in one step.
Either approach will produce the format you're expecting:
{"US10357643": {"patent_title":"System for enhanced sealing of coupled medical fluid..."}}
内容的提问来源于stack exchange,提问作者kevin

