2

I have the following code:

const result = JSON.stringify({
  drivingLicence: {
    documentNumber: '3333',
    countryOfIssue: 'UNITED_KINGDOM',
    regionOfIssue: 'UK'
  },
  mothersMaidenName: 'AAAAA',
  nationalIdentityCard: {},
  nationalInsuranceNumber: 'NW 26 52 66 A',
  passport: {}
},(key, value) =>{
  console.log(typeof key + ' ' + key);
  return value;
});

I get this output:

 console.log src/components/Submission/submissionTransformer.test.js:31
  string
console.log src/components/Submission/submissionTransformer.test.js:31
  string drivingLicence
console.log src/components/Submission/submissionTransformer.test.js:31
  string documentNumber
console.log src/components/Submission/submissionTransformer.test.js:31
  string countryOfIssue
console.log src/components/Submission/submissionTransformer.test.js:31
  string regionOfIssue
console.log src/components/Submission/submissionTransformer.test.js:31
  string mothersMaidenName
console.log src/components/Submission/submissionTransformer.test.js:31
  string nationalIdentityCard
console.log src/components/Submission/submissionTransformer.test.js:31
  string nationalInsuranceNumber
console.log src/components/Submission/submissionTransformer.test.js:31
  string passport

I do not understand where the first output is coming from.

It says the key is an empty string. Where is this coming from?

1 Answer 1

3

This is the normal behavior of JSON.stringify. From MDN:

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.

From the standard:

  1. Return ? SerializeJSONProperty(the empty String, wrapper).

That's what JSON.stringify returns. SerializeJSONProperty expects a key and a value, which it transforms to JSON using a replacer function.

Sign up to request clarification or add additional context in comments.

2 Comments

Mystified as to why it would pass an empty key and the object being stringified. Very confused by that. Thanks for clearing that up
Yeah, I can't really see why that should be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.