How to parse JSON

vancouver·2023년 5월 6일
0

HTTPS statusCode

const https = require("https");

app.get("/", function(req, res){

    const url = "https://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=84943bd3618afc411e14670414503835"

    https.get(url, function(response){
        console.log(response.statusCode); //statusCode를 넣음으로써 하이퍼터미널에서 상태코드를 확인할수있음.
    })

on callback

  response.on("data", function(data){
        console.log(data);
    })

hyper Terminal

<Buffer 7b 22 63 6f 6f 72 64 22 3a 7b 22 6c 6f 6e 22 3a 31 32 36 2e 39 37 37 38 2c 22 6c 61 74 22 3a 33 37 2e 35 36 38 33 7d 2c 22 77 65 61 74 68 65 72 22 3a ... 439 more bytes>

JSON parse

 response.on("data", function(data){
        const weatherData = JSON.parse(data)
        console.log(weatherData);

hyper Terminal

{
coord: { lon: 126.9778, lat: 37.5683 },
weather: [
{
id: 501,
main: 'Rain',
description: 'moderate rain',
icon: '10d'
}
],
base: 'stations',
main: {
temp: 13.21,
feels_like: 12.65,
temp_min: 12.66,
temp_max: 13.76,
pressure: 1009,
humidity: 79
},
visibility: 10000,
wind: { speed: 5.66, deg: 40 },
rain: { '1h': 1.59 },
clouds: { all: 75 },
dt: 1683359030,
sys: {
type: 1,
id: 8105,
country: 'KR',
sunrise: 1683318724,
sunset: 1683368723
},
timezone: 32400,
id: 1835848,
name: 'Seoul',
cod: 200
}

JSON.stringfy(object)

data를 객체화 시켜 줄일수 있다.

 response.on("data", function(data){
        const weatherData = JSON.parse(data)
        const object = {
            name: "Vancouver",
            
        }
        console.log(JSON.stringify(object));
    })

hyper Terminal

{"name":"Vancouver"}

원하는 data 뽑아내기

 response.on("data", function(data){
        const weatherData = JSON.parse(data)
        const temp = weatherData.main.temp
        console.log(temp);

hyper Terminal

  • before
    main: {
    temp: 13.21,

  • after
    13.21

 response.on("data", function(data){
 const weatherData = JSON.parse(data)
 const description = weatherData.weather[0].description
        console.log(description);

hyper Terminal

moderate rain

Reference

HTTP 상태 코드
https://developer.mozilla.org/ko/docs/Web/HTTP/Status

https.get(url[, options][, callback])
https://nodejs.org/dist/latest-v20.x/docs/api/https.html#httpsgetoptions-callback

data를 text로 변환하는 사이트
https://cryptii.com/pipes/caesar-cipher

0개의 댓글