How to Get Your IP Address in JSON Format (with Code Examples)
Back to Articles
Developer Tools

How to Get Your IP Address in JSON Format (with Code Examples)

A complete developer's guide on fetching your public IP address in structured JSON. Includes code snippets in Node.js, Python, Go, PHP, and shell scripts.

TraceThatIP Team June 1, 2026 5 min read 859 words

Introduction

As a developer, system administrator, or DevOps engineer, you frequently need to know your public IP address programmatically. Whether you are automating firewall configurations, setting up dynamic DNS (DDNS) records, logging connection metadata, or testing multi-regional server deployments, relying on manual web lookups is not an option.

While raw text endpoints are useful for basic piping in shell scripts, modern applications thrive on structured data. That is where retrieving your IP address in JSON (JavaScript Object Notation) format becomes essential.

In this comprehensive guide, we will explore why JSON is the preferred format for IP detection, how to fetch your IP in JSON using various programming languages, and how to integrate this workflow into your applications.


Why Get Your IP Address in JSON Format?

JSON is the language of the modern web. When you request your IP address in JSON, you gain several advantages over raw plain text or HTML parsing:

  1. Native Parsing: Every modern programming language—from JavaScript and Python to Go and Rust—has built-in libraries to parse JSON string structures into native objects or dictionaries.
  2. Extensibility: A plain text response only returns an IP address string (e.g., 192.0.2.1). A JSON response, however, can easily expand to include metadata like location, ISP, timezone, and ASN without breaking compatibility.
  3. Robust Error Handling: JSON payloads allow APIs to return structured error messages (e.g., {"success": false, "error": "Rate limit exceeded"}), making your integration much more resilient.
  4. Integration with Webhooks and APIs: Modern cloud services, monitoring agents, and CI/CD pipelines natively consume JSON payloads.

To see what a structured response looks like, you can visually test different formats using our IP Formatter tool, which provides instantaneous visual outputs for JSON, XML, YAML, and plain text.


How to Fetch Your IP Address in JSON (Language Examples)

Below, we have compiled verified, dependency-free (or standard-library) code examples in the most popular programming languages to query a JSON IP endpoint.

1. Bash / Command Line (cURL & jq)

If you are writing shell scripts, you can fetch your public IP in JSON format using curl. To pretty-print or parse the JSON directly in the terminal, you can pipe it to jq (a lightweight command-line JSON processor).

Terminal
# Fetch the raw JSON output
curl -s https://tracethatip.com/json

# Output:
# {
#   "ip": "203.0.113.50"
# }

If you only need the IP string from the JSON wrapper, parse it with jq:

Terminal
curl -s https://tracethatip.com/json | jq -r '.ip'

Note: For extremely lightweight shell scripts where you want to bypass JSON parsing entirely, you can query our plain-text raw endpoint directly:curl -s https://tracethatip.com/raw

2. Node.js (JavaScript)

In modern Node.js environments (v18+), you can use the native global fetch API without importing external libraries like axios or request.

JavaScript
async function getMyIpJson() {
  try {
    const response = await fetch('https://tracethatip.com/json');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log("My Public IP:", data.ip);
  } catch (error) {
    console.error("Failed to retrieve IP:", error);
  }
}

getMyIpJson();

3. Python (requests & urllib)

Python is the go-to language for automation and scripting. Here is how to retrieve your IP using the popular requests library:

Python
import requests

def get_ip_json():
    try:
        response = requests.get('https://tracethatip.com/json')
        response.raise_for_status()
        data = response.json()
        print(f"My Public IP: {data['ip']}")
    except requests.RequestException as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    get_ip_json()

If you need a standard-library-only solution that does not require installing requests:

Python
import urllib.request
import json

def get_ip_json_std():
    req = urllib.request.Request(
        'https://tracethatip.com/json', 
        headers={'User-Agent': 'Mozilla/5.0'}
    )
    try:
        with urllib.request.urlopen(req) as response:
            html = response.read().decode('utf-8')
            data = json.loads(html)
            print(f"My Public IP (urllib): {data['ip']}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == '__main__':
    get_ip_json_std()

4. Go (Golang)

Go is widely used in cloud infrastructure and microservices. Here is a robust implementation using Go's standard library:

Go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type IPResponse struct {
    IP string `json:"ip"`
}

func main() {
    client := &http.Client{Timeout: 10 * time.Second}
    req, err := http.NewRequest("GET", "https://tracethatip.com/json", nil)
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }
    req.Header.Set("User-Agent", "Go-IP-Client")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error making request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        fmt.Printf("Received non-200 status code: %d\n", resp.StatusCode)
        return
    }

    var ipResponse IPResponse
    if err := json.NewDecoder(resp.Body).Decode(&ipResponse); err != nil {
        fmt.Printf("Error parsing JSON: %v\n", err)
        return
    }

    fmt.Printf("My Public IP: %s\n", ipResponse.IP)
}

5. PHP

For web developers working on legacy or modern PHP systems, fetching and parsing JSON is simple using file_get_contents or curl.

PHP
<?php
function getPublicIpJson() {
    $url = 'https://tracethatip.com/json';
    $options = [
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: PHP-IP-Fetcher\r\n"
        ]
    ];
    $context = stream_context_create($options);
    $response = @file_get_contents($url, false, $context);
    
    if ($response === FALSE) {
        return "Error fetching IP address.";
    }
    
    $data = json_decode($response, true);
    return $data['ip'] ?? 'IP not found';
}

echo "My Public IP: " . getPublicIpJson() . "\n";
?>

Best Practices for Integrating IP Detection in Production

When using an external endpoint to detect public IPs inside your production architecture, keep these best practices in mind:

1. Implement Timeout Limits

Network latency happens. Never make synchronous blocking calls to an external IP endpoint without setting a strict timeout (e.g., 3 to 5 seconds). This prevents your application or server startup script from hanging indefinitely if routing issues occur.

2. Cache Results

Your public IP address rarely changes unless your server restarts or your ISP dynamic leases expire. To minimize external network calls and avoid rate-limiting issues, cache the detected IP locally for at least 15-30 minutes, or store it in memory.

3. Handle Proxy Headers Safely

If your application runs behind load balancers, CDN providers (like Cloudflare or Fastly), or reverse proxies (like Nginx), the standard client socket IP will point to the proxy, not the actual visitor. Be sure your backend parses proxy headers such as:

  • X-Forwarded-For
  • X-Real-IP
  • CF-Connecting-IP

4. Provide a Fallback Option

If you are developing critical server orchestration scripts, always configure a fallback endpoint or parsing method. If one server is unreachable, your scripts should gracefully fall back to a secondary verification method.


Conclusion

Getting your IP address in JSON format is the standard approach for developer automation, programmatic infrastructure monitoring, and dynamic routing updates. With the help of the examples provided above, you can seamlessly integrate IP detection into your projects.

If you are building tools that require more than just the raw IP string, try out our interactive IP Formatter page to understand formatting outputs, or use our IP Lookup tool to inspect full geographic details, ISP structures, and ASNs associated with any target IP.

Share this article