Code Examples

Using JSON in Java, JavaScript, Spring Boot & Python

Quick reference for parsing and generating JSON in popular languages.

JavaScript (browser)

In JavaScript, JSON is handled with JSON.parse and JSON.stringify.

const jsonText = '{ "name": "Alice", "age": 30 }';
const obj = JSON.parse(jsonText);
console.log(obj.name); // Alice

const out = JSON.stringify(obj, null, 2); // pretty JSON

Java with Jackson

Jackson is the most common JSON library in the Java & Spring ecosystem.

ObjectMapper mapper = new ObjectMapper();

// JSON to object
User user = mapper.readValue(jsonString, User.class);

// Object to JSON
String json = mapper.writeValueAsString(user);

Spring Boot REST controller returning JSON

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "Alice");
    }
}

Spring Boot automatically serialises the User object to JSON using Jackson.

Python with json module

import json

data = {"name": "Alice", "age": 30}

# Object to JSON string
text = json.dumps(data, indent=2)

# JSON string to object
obj = json.loads(text)
print(obj["name"])

Calling a JSON API with curl

curl -X GET "https://api.example.com/users/1" \
  -H "Accept: application/json"

Paste the response JSON into the JSON Beautifier to inspect it.

DevToolsDesk Secure, client-side tools.