Json scripts
Parsing JSON in Python
import json
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data["name"]) # Output: John
Generating JSON in Python
import json
data = {
"name": "Jane",
"age": 25,
"city": "Los Angeles"
}
json_data = json.dumps(data)
print(json_data) # Output: {"name": "Jane", "age": 25, "city": "Los Angeles"}
Parsing JSON in JavaScript
const jsonData = '{"name": "Alice", "age": 28, "city": "London"}';
const data = JSON.parse(jsonData);
console.log(data.name); // Output: Alice
Generating JSON in JavaScript
const data = {
name: "Bob",
age: 32,
city: "Paris"
};
const jsonData = JSON.stringify(data);
console.log(jsonData); // Output: {"name": "Bob", "age": 32, "city": "Paris"}
Parsing JSON in Java
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonData = "{\"name\":\"Eve\",\"age\":22,\"city\":\"Berlin\"}";
JSONObject obj = new JSONObject(jsonData);
System.out.println(obj.getString("name")); // Output: Eve
}
}
Generating JSON in Java
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "Frank");
obj.put("age", 40);
obj.put("city", "Tokyo");
String jsonData = obj.toString();
System.out.println(jsonData); // Output: {"name":"Frank","age":40,"city":"Tokyo"}
}
}
Parsing JSON in PHP
<?php
$jsonData = '{"name": "Grace", "age": 27, "city": "Rome"}';
$data = json_decode($jsonData, true);
echo $data['name']; // Output: Grace
?>
Generating JSON in PHP
<?php
$data = array(
"name" => "Henry",
"age" => 35,
"city" => "Madrid"
);
$jsonData = json_encode($data);
echo $jsonData; // Output: {"name":"Henry","age":35,"city":"Madrid"}
?>
Parsing JSON in C#
using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
string jsonData = "{\"name\":\"Ivy\",\"age\":24,\"city\":\"Dubai\"}";
var data = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonData);
Console.WriteLine(data["name"]); // Output: Ivy
}
}
Generating JSON in C#
using System;
using System.Text.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var data = new Dictionary<string, object>
{
{"name", "Jack"},
{"age", 29},
{"city", "Amsterdam"}
};
string jsonData = JsonSerializer.Serialize(data);
Console.WriteLine(jsonData); // Output: {"name":"Jack","age":29,"city":"Amsterdam"}
}
}