Skip to content

JSONファイルを読む snippet

ディスク上のJSON設定を一度の操作で使える値に読み込みます。主流のどの言語も、まさに1通りのやり方を標準搭載しているか事実上の標準として固めており、落とし穴はたいていパーサーではなくプラットフォーム側にあります。Node には fs が必要です(fetch はブラウザ用)。PHP は true を渡さない限りオブジェクトを返します。C系は事実上のライブラリ(jansson、nlohmann、serde_json)に頼ります。SQLは省略されています。ブラウザ内のSQLはローカルファイルに触れられないためです。

ディスク上のJSON設定を一度の操作で使える値に読み込みます。主流のどの言語も、まさに1通りのやり方を標準搭載しているか事実上の標準として固めており、落とし穴はたいていパーサーではなくプラットフォーム側にあります。Node には fs が必要です(fetch はブラウザ用)。PHP は true を渡さない限りオブジェクトを返します。C系は事実上のライブラリ(jansson、nlohmann、serde_json)に頼ります。SQLは省略されています。ブラウザ内のSQLはローカルファイルに触れられないためです。

Runnable recipe · 14 languagesjson-formatter ツールを開く →
Files & Datajsonfilesio

Every language

14 languages, copy-ready. One at a time with syntax highlighting, or all inline.

JSJavaScript
import { readFile } from 'node:fs/promises';

const config = JSON.parse(await readFile('config.json', 'utf8'));
console.log(config.name);

Node 18+, ESM top-level await. In the browser read `await (await fetch(url)).json()` instead — no fs there.

TSTypeScript
import { readFile } from 'node:fs/promises';

interface Config {
  name: string;
}

const config: Config = JSON.parse(await readFile('config.json', 'utf8'));
console.log(config.name);

The annotation is a trust, not a check — JSON.parse returns any. Validate untrusted files with a schema library (Zod).

GoGo
package main

import (
	"encoding/json"
	"fmt"
	"os"
)

func main() {
	data, err := os.ReadFile("config.json")
	if err != nil {
		panic(err)
	}
	var cfg struct{ Name string }
	if err := json.Unmarshal(data, &cfg); err != nil {
		panic(err)
	}
	fmt.Println(cfg.Name)
}

Unmarshal ignores unknown fields by default — extra JSON keys do not error.

RsRust
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config: serde_json::Value =
        serde_json::from_str(&fs::read_to_string("config.json")?)?;
    println!("{}", config["name"].as_str().unwrap_or(""));
    Ok(())
}

Needs serde_json = "1" in Cargo.toml — std has no JSON. Derive Deserialize on a struct for typed access.

PHPPHP
<?php
$config = json_decode(file_get_contents('config.json'), true);
echo $config['name'], PHP_EOL;

The second argument true returns associative arrays; without it you get objects and must use $config->name.

PyPython
import json

with open('config.json', encoding='utf-8') as f:
    config = json.load(f)

print(config['name'])

json.load parses straight from the file object — no read() + loads() round-trip needed.

CC
#include <jansson.h>
#include <stdio.h>

int main(void) {
    json_error_t err;
    json_t *root = json_load_file("config.json", 0, &err);
    if (!root) {
        fprintf(stderr, "%s\n", err.text);
        return 1;
    }
    const char *name = json_string_value(json_object_get(root, "name"));
    printf("%s\n", name ? name : "");
    json_decref(root);
    return 0;
}

Link with -ljansson. Standard C has no JSON parser — jansson is the small, canonical choice.

C++C++
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>

int main() {
    std::ifstream f("config.json");
    nlohmann::json config = nlohmann::json::parse(f);
    std::cout << config.at("name").get<std::string>() << '\n';
}

nlohmann/json is header-only — drop the single include into your project or fetch it via a package manager.

C#C#
using System.Text.Json;

using var doc = JsonDocument.Parse(File.ReadAllText("config.json"));
Console.WriteLine(doc.RootElement.GetProperty("name").GetString());

System.Text.Json ships with .NET. JsonDocument is IDisposable — the using disposes its pooled buffers.

JvJava
import java.nio.file.Files;
import java.nio.file.Path;
import com.google.gson.Gson;

record Config(String name) {}

public class ReadJson {
    public static void main(String[] args) throws Exception {
        String text = Files.readString(Path.of("config.json"));
        Config config = new Gson().fromJson(text, Config.class);
        System.out.println(config.name());
    }
}

Uses Gson (com.google.code.gson:gson). Jackson is the heavier, equally canonical alternative.

SwSwift
import Foundation

struct Config: Codable {
    let name: String
}

let data = try Data(contentsOf: URL(fileURLWithPath: "config.json"))
let config = try JSONDecoder().decode(Config.self, from: data)
print(config.name)

Codable gives typed access and precise errors; property names must match or be remapped with CodingKeys.

KtKotlin
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.io.File

fun main() {
    val root = Json.parseToJsonElement(File("config.json").readText()).jsonObject
    println(root["name"]?.jsonPrimitive?.content)
}

Needs kotlinx-serialization-json; parseToJsonElement keeps access dynamic, @Serializable data classes make it typed.

RbRuby
require 'json'

config = JSON.parse(File.read('config.json'))
puts config['name']

Pass symbolize_names: true to get symbol keys instead of strings.

ZigZig
const std = @import("std");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    const text = try std.fs.cwd().readFileAlloc(allocator, "config.json", 1 << 20);
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
    defer parsed.deinit();
    if (parsed.value.object.get("name")) |name| {
        std.debug.print("{s}\n", .{name.string});
    }
}

std.json is built in. The parsed value borrows the allocator's memory — deinit releases it all.

Keep going

Try the interactive json-formatter tool →Read the jq-recipes cheatsheet →