json_decode
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed
Parses a JSON string into a value.
C C23
#include <stdio.h>
#include "cJSON.h"
int main(void) {
cJSON *root = cJSON_Parse("{\"name\":\"Alice\",\"age\":30}");
if (root == NULL) { // cJSON_Parse returns NULL on failure; always check before use
fprintf(stderr, "parse failed\n");
return 1;
}
cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "name");
printf("%s", cJSON_GetStringValue(name));
cJSON_Delete(root);
return 0;
}
Alice
C++ C++26
#include <iostream>
#include "nlohmann/json.hpp"
int main() {
nlohmann::json j = nlohmann::json::parse("{\"name\":\"Alice\",\"age\":30}");
std::cout << j["name"].get<std::string>();
return 0;
}
Alice
C# v11.0.100
var d = System.Text.Json.JsonSerializer
.Deserialize<Dictionary<string, System.Text.Json.JsonElement>>("{\"name\":\"Alice\",\"age\":30}");
Console.WriteLine(d["name"]);
Alice
Go v1.27.4
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
var p Person
json.Unmarshal([]byte(`{"name":"Alice","age":30}`), &p)
fmt.Println(p.Name)
}
Alice
Java v27.0.1
import org.json.JSONObject;
class Main {
public static void main(String[] args) {
JSONObject obj = new JSONObject("{\"name\":\"Alice\",\"age\":30}");
System.out.print(obj.getString("name"));
}
}
Alice
JavaScript v26.13.1
const d = JSON.parse('{"name":"Alice","age":30}');
console.log(d.name);
Alice
PHP v8.6.0
$d = json_decode('{"name":"Alice","age":30}', true);
echo $d["name"];
Alice
Python v3.15.2
import json
d = json.loads('{"name": "Alice", "age": 30}')
print(d["name"])
Alice
Rust v1.99.1
fn main() {
// serde_json::from_str deserializes into Value (close to PHP's assoc array with the second arg true)
let v: serde_json::Value = serde_json::from_str("{\"name\":\"Alice\",\"age\":30}").unwrap();
println!("{}", v["name"].as_str().unwrap()); // as_str fetches the string content (without quotes)
}
Alice
TypeScript v26.13.1
const d = JSON.parse('{"name":"Alice","age":30}') as { name: string; age: number };
console.log(d.name);
Alice
Language differences
C: requires a third-party library for JSON — the example uses the vendored cJSON (MIT), compiled alongside the snippet.
C++: the standard library has no JSON — the example uses the vendored nlohmann/json single header: parse to decode and operator[] to read values.
C#: deserializes with System.Text.Json; a dictionary is used here.
Go: requires a predefined struct to deserialize into.
Java: the standard library has no JSON — the example uses the vendored org.json (JSONObject parses; typed getters read values).
JavaScript: JSON.parse returns an object.
PHP: json_decode returns an object (stdClass) by default; pass true as the second argument for an associative array.
Python: json.loads returns a dict.
Rust: parses with serde_json::from_str into a Value (index access resembles a PHP associative array); failures return Err.