Skip to content

Lire un fichier JSON snippet

Lire une config JSON depuis le disque vers une valeur utilisable en une étape.

Lire une config JSON depuis le disque vers une valeur utilisable en une étape. Chaque langage majeur embarque — ou a canonisé — exactement une façon de le faire, et le piège est généralement la plateforme, pas le parser : Node a besoin de fs (fetch est pour le navigateur), PHP renvoie des objets sauf si tu passes true, et la famille C s'appuie sur des bibliothèques de facto (jansson, nlohmann, serde_json). SQL est omis : le SQL de navigateur ne peut pas toucher aux fichiers locaux.

Recette exécutable · 14 langagesOpen the json-formatter tool →
Files & Datajsonfilesio

Every language

14 langages, 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 →