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

Python处理LocalBitcoins API JSON输出:获取首个价格遇阻求助

How to Properly Parse LocalBitcoins API JSON Data in Python

Hey there! I get that working with nested JSON APIs can be tricky when you're just starting out—let's fix this properly so you don't have to rely on BeautifulSoup for something the API is designed to give you directly.

Using the Requests Library (Simplest Approach)

First, let's start with the requests library since you already know it gets the full dataset. The key here is navigating the nested JSON structure correctly—this API wraps the actual ad data inside multiple layers.

Here's how to grab the first price directly:

import requests

# Fetch the JSON data
url = "https://localbitcoins.com/buy-bitcoins-online/alipay/.json"
response = requests.get(url)
api_data = response.json()

# Navigate the nested structure to get the first ad's price
first_ad_price = api_data["data"]["ad_list"][0]["data"]["temp_price"]
print(f"First available price: {first_ad_price}")

Why this works:

The API's JSON response has a top-level data key, which contains an ad_list array. Each item in that array is an ad object, and the actual details (like price) live inside another data key within each ad. If you were trying to traverse without digging into these layers, that's why you couldn't find the price!

Using Pandas to Work with the Full Dataset

Your initial pandas attempt didn't work because read_json was treating the entire top-level JSON object as a dataframe (with columns like data, pagination, etc.), instead of expanding the nested ad_list data. Here's the right way to do it:

import pandas as pd
from pandas.io.json import json_normalize
import requests

# First fetch the data with requests
url = "https://localbitcoins.com/buy-bitcoins-online/alipay/.json"
response = requests.get(url)
api_data = response.json()

# Extract the list of ads and flatten the nested data into a dataframe
ad_records = api_data["data"]["ad_list"]
df = json_normalize(ad_records, record_path="data")

# Now you can easily access the price column
print(f"First price from dataframe: {df['temp_price'].iloc[0]}")
# View the first few rows of your dataframe to see all available fields
print(df[["temp_price", "username", "countrycode"]].head())

What's happening here:

  • json_normalize helps flatten nested JSON structures into a tabular dataframe format. We specify record_path="data" to tell it to use the inner data field from each ad as the source of our rows.
  • Now you can work with all the ad data as a standard pandas dataframe, filtering, sorting, or analyzing it however you need.

This approach is way more efficient than scraping with BeautifulSoup, since you're using the API exactly as it's intended to be used.

内容的提问来源于stack exchange,提问作者Obie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:12:24