json_encode flags
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Common json_encode flags: JSON_PRETTY_PRINT for pretty printing, JSON_UNESCAPED_UNICODE to keep CJK raw, JSON_UNESCAPED_SLASHES to keep slashes raw.
C C23
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main(void) {
cJSON *tags = cJSON_CreateArray();
cJSON_AddItemToArray(tags, cJSON_CreateString("php"));
cJSON_AddItemToArray(tags, cJSON_CreateString("json"));
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "name", "张伟");
cJSON_AddStringToObject(root, "url", "https://codeabc.dev/api");
cJSON_AddItemToObject(root, "tags", tags);
char *out = cJSON_Print(root); // pretty print: tab indent, short arrays stay inline
printf("%s", out);
cJSON_free(out);
cJSON_Delete(root);
return 0;
}
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": ["php", "json"]
}
C++ C++26
#include <iostream>
#include "nlohmann/json.hpp"
int main() {
// ordered_json keeps insertion order; dump(4) pretty-prints with 4-space indent
nlohmann::ordered_json j;
j["name"] = "张伟";
j["url"] = "https://codeabc.dev/api";
j["tags"] = {"php", "json"};
std::cout << j.dump(4); // non-ASCII and slashes stay raw by default
return 0;
}
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
C# v11.0.100
using System.Text.Encodings.Web;
using System.Text.Json;
var data = new Dictionary<string, object> {
["name"] = "张伟",
["url"] = "https://codeabc.dev/api",
["tags"] = new[] { "php", "json" },
};
var opts = new JsonSerializerOptions {
WriteIndented = true, // = JSON_PRETTY_PRINT
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, // = UNESCAPED_UNICODE | UNESCAPED_SLASHES
IndentSize = 4,
};
Console.WriteLine(JsonSerializer.Serialize(data, opts));
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
Go v1.27.4
package main
import (
"encoding/json"
"fmt"
)
type Item struct {
Name string `json:"name"`
URL string `json:"url"`
Tags []string `json:"tags"`
}
func main() {
// MarshalIndent = pretty print; Go never escapes non-ASCII or slashes
b, _ := json.MarshalIndent(Item{Name: "张伟", URL: "https://codeabc.dev/api", Tags: []string{"php", "json"}}, "", " ")
fmt.Println(string(b))
}
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
Java v27.0.1
import java.util.Arrays;
import org.json.JSONArray;
public class Main {
public static void main(String[] args) {
// top-level arrays keep order (org.json's JSONObject is HashMap-based, keys unordered)
JSONArray rows = new JSONArray();
rows.put(new JSONArray(Arrays.asList("张伟", "https://codeabc.dev/api")));
rows.put(new JSONArray(Arrays.asList("李娜", "https://codeabc.dev/docs")));
System.out.println(rows.toString(4)); // toString(4) pretty-prints
}
}
[
[
"张伟",
"https://codeabc.dev/api"
],
[
"李娜",
"https://codeabc.dev/docs"
]
]
JavaScript v26.13.1
// JSON.stringify keeps non-ASCII and slashes raw anyway; indent = pretty print
const data = { name: "张伟", url: "https://codeabc.dev/api", tags: ["php", "json"] };
console.log(JSON.stringify(data, null, 4));
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
PHP v8.6.0
$data = ['name' => '张伟', 'url' => 'https://codeabc.dev/api', 'tags' => ['php', 'json']];
// pretty 4-space indent + keep CJK raw + keep slashes raw
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
Python v3.15.2
import json
data = {"name": "张伟", "url": "https://codeabc.dev/api", "tags": ["php", "json"]}
# ensure_ascii=False keeps CJK raw; indent=4 pretty-prints (slashes never escaped)
print(json.dumps(data, ensure_ascii=False, indent=4))
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
Rust v1.99.1
fn main() {
// to_string_pretty = pretty print (fixed 2-space indent); CJK and slashes stay raw
let j = serde_json::json!({
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": ["php", "json"]
});
println!("{}", serde_json::to_string_pretty(&j).unwrap());
}
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
TypeScript v26.13.1
// JSON.stringify keeps non-ASCII and slashes raw anyway; indent = pretty print
const data: Record<string, unknown> = { name: "张伟", url: "https://codeabc.dev/api", tags: ["php", "json"] };
console.log(JSON.stringify(data, null, 4));
{
"name": "张伟",
"url": "https://codeabc.dev/api",
"tags": [
"php",
"json"
]
}
Language differences
C: cJSON_Print's pretty style is one of a kind (example) — tab indentation, a tab after the colon too, and short arrays kept inline; non-ASCII and slashes pass through as raw UTF-8 bytes; cJSON_PrintUnformatted corresponds to the default compact mode.
C++: dump(4) is 4-space pretty printing (example), byte-identical to PHP's three-flag combo; dump(-1) is compact and dump(4, ' ', true) is the ensure_ascii variant — by default CJK stays raw.
C#: the default Encoder escapes non-ASCII (\u5f20\u4f1f) and WriteIndented is a fixed 2 spaces — UnsafeRelaxedJsonEscaping + IndentSize = 4 (example) is needed to align with PHP's output; relaxed is only for outputs guaranteed to be non-HTML contexts.
Go: MarshalIndent is pretty printing (example) with a selectable indent string; Go never escapes non-ASCII or slashes, but it does escape < > & by default (HTML safety) — for URLs containing those, use a json.Encoder with SetEscapeHTML(false).
Java: org.json's toString(indentFactor) pretty-prints (example) — but JSONObject is HashMap-based with no key-order contract, so the example uses an all-array structure for deterministic order; arrays/lists keep order, string values keep CJK raw, and slashes are escaped only after a <.
JavaScript: JSON.stringify(data, null, 4) (example) — the third argument is the PRETTY_PRINT equivalent (0-10 spaces or a string); JS never escapes CJK or slashes, so its default output already equals all three flags on.
PHP: by default json_encode escapes CJK as \uXXXX and slashes as \/ (a legacy HTML-safety burden); the three-flag combo (example) yields human-readable, diffable JSON; logging/debugging should always add JSON_UNESCAPED_UNICODE or CJK logs become unreadable.
Python: ensure_ascii=False + indent=4 (example) map to no-CJK-escaping and pretty printing respectively; Python never escapes slashes; sort_keys=True gives order-stable output.
Rust: to_string_pretty pretty-prints (example) — the 2-space indent is fixed and unconfigurable; serde_json leaves non-ASCII and slashes raw by default; compact to_string corresponds to default json_encode.
TypeScript: same as JavaScript; note the JSON.stringify(data, null, "\t") tab-indent variant — the indent string is capped at 10 characters.