You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将grant_id设为索引输出指定格式的JSON?

How to Use 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 (treating grant_id/patent_title as rows instead of columns). By first building a standard column-based DataFrame, then setting grant_id as the index, we ensure the JSON uses those IDs as keys.
  • The orient='index' parameter in to_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:06:54