Site icon LIVETUTU

JSON Introduction

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is text, written with JavaScript object notation.

Sample JSON

example 1

{
"name": "Test",
"age": 30,
"city": "cityname"
}

example 2

[
    {
        "name": "test1",
        "age": 30,
        "city": "cityname1"
    },
    {
        "name": "test2",
        "age": 25,
        "city": "cityname2"
    }
]

Why Use JSON?

How to Use JSON in python

import json

# Example JSON data
data = {
    "name": "test",
    "age": 30,
    "city": "cityname"
}

# Convert Python object to JSON string
json_string = json.dumps(data)
print(json_string)

# Convert JSON string to Python object
parsed_data = json.loads(json_string)
print(parsed_data)

How to Use JSON in React

import React, { useState, useEffect } from 'react';

const App = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch('https://api.example.com/data');
            const result = await response.json();
            setData(result);
        };

        fetchData();
    }, []);

    return (
        <div>
            {data ? (
                <div>
                    <h1>{data.name}</h1>
                    <p>Age: {data.age}</p>
                    <p>City: {data.city}</p>
                </div>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};

export default App;


How to Use JSON in React Native

import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';

const App = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            const response = await fetch('https://api.example.com/data');
            const result = await response.json();
            setData(result);
        };

        fetchData();
    }, []);

    return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
            {data ? (
                <View>
                    <Text>Name: {data.name}</Text>
                    <Text>Age: {data.age}</Text>
                    <Text>City: {data.city}</Text>
                </View>
            ) : (
                <ActivityIndicator size="large" color="#0000ff" />
            )}
        </View>
    );
};

export default App;

How to Use JSON in Kotlin

import org.json.JSONObject

fun main() {
    val jsonString = """
        {
            "name": "test",
            "age": 30,
            "city": "cityname"
        }
    """.trimIndent()

    // Parse JSON string to JSONObject
    val jsonObject = JSONObject(jsonString)

    // Access data
    val name = jsonObject.getString("name")
    val age = jsonObject.getInt("age")
    val city = jsonObject.getString("city")

    println("Name: $name, Age: $age, City: $city")

    // Convert JSONObject to JSON string
    val newJsonString = jsonObject.toString()
    println(newJsonString)
}

How to Use JSON in JavaScript

const jsonString = '{"name":"test","age":30,"city":"cityname"}';

// Parse JSON string to JavaScript object
const data = JSON.parse(jsonString);

console.log(data.name); // Output: test
console.log(data.age);  // Output: 30
console.log(data.city); // Output: cityname

// Convert JavaScript object to JSON string
const newJsonString = JSON.stringify(data);
console.log(newJsonString);

How to Use JSON in SwiftUI

  1. Create the Model:
import Foundation

struct User: Codable, Identifiable {
    let id = UUID()
    let name: String
    let age: Int
    let city: String
}

2. Fetch and Parse JSON

import SwiftUI

struct ContentView: View {
    @State private var users: [User] = []

    var body: some View {
        List(users) { user in
            VStack(alignment: .leading) {
                Text(user.name).font(.headline)
                Text("Age: \(user.age)")
                Text("City: \(user.city)")
            }
        }
        .onAppear(perform: loadData)
    }

    func loadData() {
        guard let url = URL(string: "https://api.example.com/users") else {
            print("Invalid URL")
            return
        }

        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        self.users = decodedResponse
                    }
                } else {
                    print("Failed to decode JSON")
                }
            }
        }.resume()
    }
}

JSON Tools

Exit mobile version