본문 바로가기
개념/혼자 공부하는 Javascript

method) JSON.stringify() method

by kiseno 2025. 1. 19.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        const data = [{
            name : '혼공 파이썬',
            price : 10000,
            publisher : '한빛미디어'
        }, {
            name : 'HTML5 web programming',
            price : 20000,
            publisher : '한빛아카데미'
        }]

        console.log(JSON.stringify(data))
        console.log(JSON.stringify(data, null, 2))
    </script>
</head>
<body>

</body>
</html>

1. **Without Formatting**: The first `console.log` call uses `JSON.stringify(data)` to convert the `data` array to a JSON string without any additional formatting. The resulting JSON string will be compact without any spaces or indentation, making it ideal for data transmission where minimizing the size is important.

2. **With Formatting**: The second `console.log` call uses `JSON.stringify(data, null, 2)` to convert the `data` array to a JSON string with formatting. The first additional argument, `null`, is a replacer function that, in this case, is not used (hence `null`). The second argument, `2`, specifies the number of spaces to use for indentation. This makes the output more readable, which is useful for debugging or displaying the JSON in a more understandable format.

### Example Output
- **First `console.log` output (without formatting)**:
```json
[{"name":"혼공 파이썬","price":10000,"publisher":"한빛미디어"},{"name":"HTML5 web programming","price":20000,"publisher":"한빛아카데미"}]
```

- **Second `console.log` output (with formatting)**:
```

[
  {
    "name": "혼공 파이썬",
    "price": 10000,
    "publisher": "한빛미디어"
  },
  {
    "name": "HTML5 web programming",
    "price": 20000,
    "publisher": "한빛아카데미"
  }
]


```

### Summary
The use of `JSON.stringify` with and without the indentation parameter demonstrates how JavaScript provides flexibility in how data is serialized to JSON. The choice between these methods depends on the use case—compact data for efficient transmission or readable data for debugging and presentation. This example clearly illustrates how to utilize both forms based on the needs of your application or development process.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

method) getter and setter method  (0) 2025.01.21
method) JSON.parse() method  (0) 2025.01.20
method) Lodash_sortBy() method  (1) 2025.01.18
method) map() method  (0) 2025.01.17
method) Math.random() method  (0) 2025.01.16