DEV Community

Imad Uddin
Imad Uddin

Posted on

How to Add an Image to a JSON Object — 3 Methods with Examples

There's no native "image type" in JSON. But there are three practical ways to include image data — and each has a clear use case.

Method 1: URL reference (most common)

{
  "id": 1,
  "name": "Product A",
  "image_url": "https://cdn.example.com/images/product-a.jpg"
}
Enter fullscreen mode Exit fullscreen mode

✅ Small payload, cacheable, CDN-friendly
❌ Requires internet access, image host must stay up

Use this for: REST APIs, e-commerce, any web app

Method 2: File path (local apps)

{
  "name": "Avatar",
  "image_path": "./assets/images/avatar.png"
}
Enter fullscreen mode Exit fullscreen mode

✅ No internet needed, fast local access
❌ Path breaks on other machines, not portable

Use this for: Desktop apps, game engines, bundled assets

Method 3: Base64 encoding (self-contained)

// Convert image to base64 in Node.js
const fs = require("fs");
const base64 = fs.readFileSync("avatar.png").toString("base64");

const json = {
  name: "Avatar",
  image_data: `data:image/png;base64,${base64}`
};
Enter fullscreen mode Exit fullscreen mode
{
  "name": "Avatar",
  "image_data": "data:image/png;base64,iVBORw0KGgoAAAANS..."
}
Enter fullscreen mode Exit fullscreen mode

✅ Fully self-contained, works offline
❌ Bloats payload significantly, bad for many images

Use this for: Email templates, offline apps, single-file exports

Quick decision guide

Scenario Method
Public web API URL
Desktop/mobile app File path
Offline / embedded Base64

Full guide with best practices: How to Add an Image in JSON

Top comments (0)