There's Way More to JSON.Stringify Than You Think

dcode
17 Sept 202409:26

Summary

TLDRIn this video, Dom explores the intricacies of JavaScript's JSON.stringify method, revealing its hidden capabilities. He demonstrates how to prettify JSON output with indentation and new lines using the third argument, and delves into the second argument's role in filtering object properties for JSON conversion. Dom also explains the use of replacer functions to filter or transform data, showcasing practical examples. The video is an insightful guide for developers looking to harness the full potential of JSON.stringify.

Takeaways

  • 🔍 The `JSON.stringify` method in JavaScript converts objects or arrays into JSON strings.
  • 📄 To make the JSON output more readable, you can use the third argument of `JSON.stringify` to add indentation with a specified number of spaces or a string like tabs.
  • 🚫 The second argument of `JSON.stringify` can be an array specifying a whitelist of properties to include in the JSON output, useful for filtering sensitive data.
  • 👨‍💻 Passing a function as the second argument allows for custom filtering and transformation of the JSON output, acting as a replacer function that runs for each property.
  • 🔑 The replacer function is first called for the entire object, and then for each property, making it possible to manipulate the entire structure or individual values.
  • 🛠️ Using the replacer function, you can filter out properties by returning `undefined` for certain conditions or transform values, such as multiplying numbers by a factor.
  • 📊 The replacer function provides a powerful way to control the serialization process, allowing for both inclusion/exclusion of data and value transformations.
  • 💡 While the replacer function is versatile, it's often simpler to create a new object with the desired properties before stringifying, especially for complex transformations.
  • 👍 The video provides practical examples of how to use `JSON.stringify` with different arguments, demonstrating the method's flexibility in generating JSON strings.

Q & A

  • What is the primary function of JSON.stringify in JavaScript?

    -JSON.stringify in JavaScript is used to convert an object or an array into a JSON string.

  • How can you prettify the JSON string output using JSON.stringify?

    -You can prettify the JSON string by using the third argument of JSON.stringify, which allows you to specify the number of spaces for indentation or a string like a tab character.

  • What is the maximum indentation level allowed when using the third argument in JSON.stringify?

    -The maximum indentation level allowed is 10 spaces, regardless of the number specified.

  • What does the second argument of JSON.stringify do when it's an array?

    -When the second argument is an array, it acts as a whitelist to specify which properties of an object to include in the JSON string output.

  • What happens if you provide an empty array as the second argument in JSON.stringify?

    -Providing an empty array as the second argument results in no properties being included in the JSON string output.

  • Can you use a function as the second argument in JSON.stringify, and if so, what does it do?

    -Yes, a function can be used as the second argument, and it acts as a filter to determine which values are included in the JSON string by returning them, or it can transform the values by returning modified versions.

  • What is the behavior of the replacer function when it encounters the initial call with an empty key?

    -The replacer function is initially called with an empty key for the entire object, and if it returns the object itself, it proceeds to process each property.

  • How can you use the replacer function to filter out properties from the JSON string?

    -You can use the replacer function to filter out properties by returning 'undefined' for the properties you want to exclude from the JSON string.

  • Is it possible to modify the values during the JSON.stringify process using the replacer function?

    -Yes, you can modify the values by returning a transformed version of the value within the replacer function.

  • Why might someone choose to create a new object before using JSON.stringify instead of using the replacer function?

    -Creating a new object before using JSON.stringify might be preferred for clarity and simplicity, especially when the transformations or filtering are complex or numerous.

Outlines

00:00

🔍 Deep Dive into JSON.stringify in JavaScript

In this segment, Dom introduces the JSON.stringify function in JavaScript, explaining its basic use for converting objects or arrays into JSON strings. He demonstrates how to use the function with an example user object, showcasing how to prettify the JSON output with indentation and new lines by using the third argument, which can be a number for space-based indentation or a string, such as a tab character, for tab-based indentation. Dom also hints at the more advanced features of the second argument, which he will explore later in the video.

05:05

🛠 Customizing JSON.stringify with Replacer Functions

Dom continues the exploration of JSON.stringify by focusing on the second argument, which can be used to filter or transform the JSON output. He explains that an array can be provided to act as a whitelist for properties to include, or a function can be used for more complex filtering and transformations. Dom creates a replacer function that initially returns the value directly, which has no effect on the output. He then modifies the function to return 'decode' for all properties, demonstrating that the replacer function is called for the entire object first, and then for each property. By adding conditions to the replacer function, Dom shows how it can be used to filter out properties or to manipulate property values, such as doubling the value of numerical properties. This part of the video provides a detailed look at the versatility of the replacer function in JSON.stringify.

Mindmap

Keywords

💡JSON.stringify

JSON.stringify is a JavaScript method that converts a JavaScript object or array into a JSON string. It's a crucial function for data serialization, allowing for easy data transfer between a frontend and backend or storage. In the video, it's used to demonstrate how to convert a user object with properties into a JSON string, which is then logged to the console.

💡Prettify

Prettify refers to the process of formatting code or data to make it more readable. In the context of JSON.stringify, prettifying a JSON string means adding indentation and new lines to make the structure clear. The video explains how to use the third argument of JSON.stringify to achieve this, enhancing the human readability of the JSON output.

💡Indentation

Indentation is the space used to structure text, typically to indicate levels of nesting in code. In JSON.stringify, indentation is controlled by the third argument, which can be a number specifying the number of spaces or a string such as a tab character. The video demonstrates how to use this feature to format JSON data with different levels of indentation.

💡Replacer

The replacer in JSON.stringify is a second optional argument that can be an array or a function. It determines how the object is stringified. If an array, it acts as a whitelist of properties to include. If a function, it filters or transforms the values. The video illustrates both uses, showing how to selectively include properties and how to manipulate values before they're converted to JSON.

💡Whitelist

A whitelist in the context of JSON.stringify is an array of property names that the replacer argument specifies should be included in the JSON string output. This is used to filter the object's properties, ensuring only certain values are serialized. The video uses an example where only 'memberSince' and 'ID' are included, demonstrating how to create a whitelist.

💡Transformation

Transformation refers to the process of modifying data. In JSON.stringify, when a function is used as the replacer, it can transform the values of the object's properties before they are converted to JSON. The video gives an example where numeric values are doubled, showing how the replacer function can be used for data manipulation.

💡Filter

Filtering in JSON.stringify is achieved through the replacer function, which can return 'undefined' for properties that should not be included in the JSON string. This acts as a filter, allowing for conditional inclusion of data. The video demonstrates filtering by only including properties with string values.

💡Console.log

Console.log is a JavaScript function used to output information to the web browser's console. In the video, console.log is used to display the results of JSON.stringify, allowing the viewer to see the JSON string representation of the object and the effects of prettification and filtering.

💡Serialization

Serialization is the process of converting an object into a format that can be easily stored or transmitted, such as a JSON string. JSON.stringify is a serialization method for JavaScript objects. The video explains how objects are serialized into JSON, which is a lightweight data-interchange format.

💡Data Manipulation

Data manipulation involves altering data structures or values. In the context of the video, data manipulation is shown through the use of the replacer function in JSON.stringify, where values can be changed or filtered out before serialization. This is useful for preparing data for specific uses, such as adjusting numerical values or excluding sensitive information.

💡Sensitive Information

Sensitive information refers to data that should be protected or hidden due to privacy concerns. In the video, the concept is mentioned in relation to the replacer function, which can be used to exclude sensitive properties like IDs or tokens from the JSON string output before it's sent to a server.

Highlights

Introduction to JSON.stringify in JavaScript and its capabilities.

JSON.stringify converts objects or arrays into JSON strings.

Demonstration of JSON.stringify with a user object example.

Using JSON.stringify to prettify JSON with indentation.

The third argument in JSON.stringify for indentation control.

Limitation of indentation to a maximum of 10 spaces.

Option to use a string, like 'tab', for indentation instead of spaces.

The second argument in JSON.stringify for filtering object properties.

Whitelisting properties to keep in the JSON output using an array.

Using an empty array results in no data in the JSON output.

The replacer function as the second argument for filtering and transforming JSON data.

The replacer function is called for every property and the entire object.

Returning 'undefined' from the replacer function excludes properties from the output.

Using the replacer function to manipulate data, such as doubling numbers.

Practical use case of the replacer function for sensitive data filtering.

The option to create a new object for transformations before JSON.stringify.

Conclusion and summary of JSON.stringify features discussed.

Transcripts

play00:00

how's it going guys my name is Dom and

play00:01

today we're going to be doing a bit of a

play00:03

deep dive into json. stringify in

play00:06

JavaScript because it actually has quite

play00:08

a few really nice hidden gems okay so

play00:11

just as a quick recap here Json Stringer

play00:14

fire is going to take an object or an

play00:16

array then convert it into a Json string

play00:19

for example I've got this user object

play00:21

right here with five properties on it if

play00:24

I was to console log json. stringify the

play00:27

user object we of course are going to

play00:29

get the Json version of that object

play00:32

right here in the console as you can see

play00:34

it is all condensed onto a single line

play00:38

but you can use Json stringify to

play00:40

prettify this Json give it indentation

play00:43

and so on that is going to be done using

play00:46

the third argument to this function here

play00:49

but the most interesting part is the

play00:51

second argument and I'm going to be

play00:53

showing you that towards the later part

play00:55

of this video so first let's have a look

play00:57

at how to uh prettify this Json so let's

play01:02

provide null as the second argument like

play01:05

I said we're going to be coming back to

play01:07

this one very shortly for the third

play01:09

argument let's use the number two what

play01:13

this does here is I to console log now

play01:16

we can see we get

play01:17

indentation uh and new lines and so on

play01:21

okay this here is the number of spaces

play01:24

to use for indentation so we get one and

play01:27

two you can say for example example six

play01:31

I'll try it again now we get more space

play01:33

there of course six spaces for each

play01:36

indentation of course 12 uh when it

play01:40

requires two levels of

play01:41

indentation now this here is going to

play01:43

max out at 10 so even if you were to say

play01:46

for example 4,000 it's only going to uh

play01:50

you know go up to 10 and then stop there

play01:52

as the max so now we can see we only get

play01:55

10 here as opposed to of course 4,000 as

play01:58

the indentation so that is your spaces

play02:02

version of uh this particular feature

play02:04

here but you can also provide a string

play02:07

okay the most common string being used

play02:10

is going to be the tab character so I

play02:12

can say back SLT this here is now going

play02:14

to use tabs for the indentation as

play02:17

opposed to spaces and it's hard to know

play02:20

if it's actually tabs in the console

play02:22

here but trust me it is definitely going

play02:24

to be tabs when you H go ahead and use

play02:26

it you can also say double tab for

play02:29

example some something like this not

play02:31

sure why you want to do this but you can

play02:33

see it does definitely work okay you can

play02:36

actually provide whatever string you

play02:37

want here for example decode is also

play02:39

going to be perfectly valid I'll try it

play02:42

again now we get decode the string as

play02:45

the indentation between every single

play02:47

level so I think for the most part

play02:49

you're only going to be really using a

play02:51

back SLT or tab character here um for

play02:54

the majority of situations and there we

play02:57

go now let's jump to this second

play03:00

argument right here this applies mostly

play03:04

if not all the time to uh objects when

play03:07

you're trying to convert yeah objects to

play03:09

Json and not arrays now what is the

play03:12

second argument well you can provide two

play03:15

different types of values to this

play03:18

similar to the third one now having a

play03:20

look at what happens when you provide an

play03:22

array to this argument this here is

play03:26

going to uh specify a white list of what

play03:30

to keep in the output for example if I

play03:33

was to say member since okay and also

play03:38

let's just do ID now I'll try it again

play03:42

console log it's only going to give us

play03:45

member SN and ID whatever goes in here

play03:49

this or these properties are going to be

play03:51

included in the output okay for example

play03:55

if you also were to provide an empty

play03:57

array in this case you're going to get

play03:59

no dat um in the output so there you go

play04:02

it's a white list of what to keep okay

play04:05

this here might be useful if you want to

play04:08

emit certain values like maybe think

play04:10

about things like IDs or tokens or

play04:13

anything other that might be sensitive

play04:15

before sending to your server side maybe

play04:18

things like that um and that's of course

play04:20

if you don't go ahead and make a new

play04:22

object instead before passing it to your

play04:24

Json string ofile but of course this

play04:26

here is just going to be an option if

play04:28

you want to use it okay okay now that is

play04:31

the array version of that second

play04:33

argument what if you were to provide a

play04:35

function instead let's have a look so

play04:39

let's create a new constant here called

play04:42

replacer this is going to be the

play04:44

function which we're going to be passing

play04:46

in to the second argument let's say here

play04:49

key and value and for now let's just

play04:53

return um let's just return value so

play04:56

this here acts as kind of like a filter

play04:59

in a way um to your Json stringify so

play05:05

we're going to take this function and

play05:07

then reference it as the second argument

play05:09

right here like this and we can see that

play05:11

returning value directly is going to

play05:14

have no effect on the output and there

play05:16

we go okay but what is this actually

play05:18

doing well this function okay is going

play05:23

to run for all your properties so all

play05:26

these five properties here Whatever Gets

play05:29

returned that's going to be what the

play05:30

value is in your Json uh output okay

play05:34

let's say return and let's do decode

play05:37

instead now something strange will

play05:40

happen here but let's just try it anyway

play05:43

we actually just get decode okay that's

play05:46

because this replacer also runs for the

play05:50

entire object itself okay so I'll repeat

play05:56

that when you provide replacer you're

play06:00

going to get a function call for the

play06:04

entire object so what's happened here is

play06:08

we're saying look let's run replacer it

play06:10

runs on the entire object first then it

play06:12

just simply returns decode which is why

play06:14

we get decode right here okay to make

play06:17

things easier to understand let's say if

play06:21

key is equal to empty string then return

play06:25

value okay because your key is going to

play06:28

be every single property here and the

play06:32

key being an empty string is the first

play06:34

one the initial one that's when it's for

play06:36

the whole object meaning now F to save

play06:39

this Runner again we get the whole thing

play06:42

returned back this time right because we

play06:45

return the object back then it goes

play06:47

ahead and proceeds and then does this

play06:49

for every other property and we get

play06:51

decode as the output able to manipulate

play06:54

or replace transform the values in the

play06:57

Json to make this interesting you might

play07:01

say for example I want to only keep the

play07:06

strings um you know or sorry I only keep

play07:08

the properties with the string as the

play07:10

value okay so in that case I might say

play07:13

okay no worries if type of value does

play07:18

not equal to be

play07:21

string then we're going to return

play07:24

undefined otherwise simply return the

play07:27

value like that so this here is going to

play07:30

run for ID okay in this case ID is a

play07:34

string so this won't run and you simply

play07:36

return the value so in this case of

play07:38

course A8 EF know 4 Etc same goes for

play07:42

display name and username they of course

play07:44

they're all strings so it's going to

play07:45

work you get to remember since okay it's

play07:47

going to say okay noris if type of uh

play07:51

2017 is not a string yes return

play07:54

undefined because we return undefined

play07:57

this here is going to emit it from the

play07:58

output I'll run the script again and now

play08:01

we can see we only get those string

play08:04

values in the output right there okay so

play08:08

you can use it to filter your values

play08:11

like this return undefined and return

play08:13

the value with conditions Etc or you can

play08:16

use it to manipulate your data

play08:20

okay uh so you could say let's just do a

play08:22

quick example here if type of value is

play08:25

equal to number okay if it's a number

play08:29

then just say return value time 2 okay

play08:33

let's try this now and we get member

play08:36

since

play08:37

4034 instead of 2017 of course that is

play08:41

that number multiplied by two so you can

play08:43

see that he can also do Transformations

play08:46

as part of the replacer now if I'm being

play08:49

honest you probably won't use this very

play08:51

often and it's a similar story to

play08:54

providing the array in that you probably

play08:57

just create a new object up here

play08:59

beforehand and do your Transformations

play09:02

and your uh when you want to get rid of

play09:04

your keys and things like that remove

play09:07

your keys so unlikely you want to be

play09:10

using this but look the option is there

play09:12

for you to use and it's a bit

play09:13

interesting um to see it in action so

play09:15

that is the Json stringify function in a

play09:18

bit more detail if this video helped you

play09:20

out make sure to drop a like And

play09:22

subscribe to decode and here is another

play09:25

video

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
JavaScriptJSON.stringifyCode TutorialWeb DevelopmentData SerializationProgramming TipsCode OptimizationDeveloper ToolsJSON ParsingCode Techniques
Benötigen Sie eine Zusammenfassung auf Englisch?