Skip to content

feat: add @stdlib/utils/jsonify-keys #5415

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 157 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<!--

@license Apache-2.0

Copyright (c) 2025 The Stdlib Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

# JSONify keys

> Parse a [JSON][json]-like string as [JSON][json].
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

im open to changing this to a more accurate description if you have any suggestions @kgryte!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait...wasn't the original idea to simply normalize a JSON-like string to something that could be parsed as JSON? This looks to both normalize and parse, which is more than is likely needed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, the idea of jsonify-keys should be to normalize a string. That string could then be separately passed to utils/parse-json through composition. Normalization and parsing are two separate operations.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noted! pushing the required changes soon.


<section class="usage">

## Usage

```javascript
var jsonifyKeys = require( '@stdlib/utils/jsonify-keys' );
```

#### jsonifyKeys( str\[, reviver] )

Parses a [JSON][json]-like `string` as [JSON][json].

```javascript
var out = jsonifyKeys( '{"beep":"boop"}' );
// returns {'beep':'boop'}
```

If unable to parse a `string` as [JSON][json], the function returns an error.

```javascript
var out = jsonifyKeys( 'beep' );
// returns <SyntaxError>
```

To transform the `string` being parsed, provide a `reviver`.

```javascript
function reviver( key, value ) {
if ( key === '' ) {
return value;
}
if ( key === 'beep' ) {
return value;
}
}

var str = '{ beep: "boop", a: "b"}';
var out = jsonifyKeys( str, reviver );
// returns {'beep':'boop'}
```

</section>

<!-- /.usage -->

<section class="notes">

## Notes

- In contrast to the native [`JSON.parse()`][json-parse], this implementation throws a `TypeError` if provided **any** value which is not a `string`.

```javascript
var out = JSON.parse( null );
// returns null

out = jsonifyKeys( null );
// throws <TypeError>
```

- In contrast to the native [`JSON.parse()`][json-parse], this implementation does **not** throw a `SyntaxError` if unable to parse a `string` as [JSON][json].

```javascript
var out = jsonifyKeys( '{ beep: "boop}' );
// returns <SyntaxError>

out = JSON.parse( '{ "beep": "boop}' );
// throws <SyntaxError>
```

- In contrast to the native [`JSON.parse()`][json-parse], this implementation throws a `TypeError` if provided a `reviver` argument which is **not** a `function`.

```javascript
var out = JSON.parse( '{"a":"b"}', [] );
// returns {'a':'b'}

out = jsonifyKeys( '{ a: "b"}', [] );
// throws <TypeError>
```

</section>

<!-- /.notes -->

<section class="examples">

## Examples

<!-- eslint no-undef: "error" -->

```javascript
var jsonifyKeys = require( '@stdlib/utils/jsonify-keys' );

var out;

out = jsonifyKeys( '{ beep: "boop"}' );
// returns {'beep':'boop'}

out = jsonifyKeys( '3.14' );
// returns 3.14

out = jsonifyKeys( 'true' );
// returns true

out = jsonifyKeys( 'null' );
// returns null

out = jsonifyKeys( '{"beep":"boop}' );
// returns <SyntaxError>
```

</section>

<!-- /.examples -->

<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->

<section class="related">

</section>

<!-- /.related -->

<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="links">

[json]: http://www.json.org/

[json-parse]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

</section>

<!-- /.links -->
50 changes: 50 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/benchmark/benchmark.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* @license Apache-2.0
*
* Copyright (c) 2025 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var pkg = require( './../package.json' ).name;
var jsonifyKeys = require( './../lib' );


// MAIN //

bench( pkg, function benchmark( b ) {
var str;
var out;
var i;

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
str = '{ beep: "boop",'+fromCodePoint( 97 + (i%26) ) + ':true}';
out = jsonifyKeys( str );
if ( out instanceof Error ) {
b.fail( out.message );
}
}
b.toc();
if ( out instanceof Error ) {
b.fail( 'should return JSON' );
}
b.pass( 'benchmark finished' );
b.end();
});
41 changes: 41 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/docs/repl.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

{{alias}}( str[, reviver] )
Attempts to parse a JSON-like string as JSON.

Function behavior differs from `JSON.parse()` as follows:

- throws a `TypeError` if provided any value which is not a string.
- throws a `TypeError` if provided a `reviver` argument which is not a
function.
- returns, rather than throws, a `SyntaxError` if unable to parse a string
as JSON.

Parameters
----------
str: string
String to parse.

reviver: Function (optional)
Transformation function.

Returns
-------
out: any|Error
Parsed value or an error.

Examples
--------
> var obj = {{alias}}( '{ beep: "boop"}' )
{ 'beep': 'boop' }

// Provide a reviver:
> function reviver( key, value ) {
... if ( key === '' ) { return value; }
... if ( key === 'beep' ) { return value; }
... };
> var str = '{ beep: "boop", a: "b" }';
> var out = {{alias}}( str, reviver )
{ 'beep': 'boop' }

See Also
--------
37 changes: 37 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/docs/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* @license Apache-2.0
*
* Copyright (c) 2025 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// TypeScript Version: 4.1

/**
* Attempts to parse a JSON-like string as JSON.
*
* @param str - string to parse
* @param reviver - transformation function
* @returns parsed value or parse error
*
* @example
* var obj = jsonifyKeys( '{ beep: "boop" }' );
* // returns {'beep':'boop'}
*/
declare function jsonifyKeys( str: string, reviver?: Function ): any;

Check warning on line 32 in lib/node_modules/@stdlib/utils/jsonify-keys/docs/types/index.d.ts

View workflow job for this annotation

GitHub Actions / Lint Changed Files

Unexpected any. Specify a different type


// EXPORTS //

export = jsonifyKeys;
55 changes: 55 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/docs/types/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* @license Apache-2.0
*
* Copyright (c) 2025 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import jsonifyKeys = require( './index' );


// TESTS //

// The function returns a parsed value...
{
jsonifyKeys( '{beep:"boop"}' ); // $ExpectType any
jsonifyKeys( '"beep"' ); // $ExpectType any
jsonifyKeys( '22' ); // $ExpectType any
}

// The function does not compile if the first argument is a value other than a string...
{
jsonifyKeys( true ); // $ExpectError
jsonifyKeys( false ); // $ExpectError
jsonifyKeys( 5 ); // $ExpectError
jsonifyKeys( [] ); // $ExpectError
jsonifyKeys( {} ); // $ExpectError
jsonifyKeys( ( x: number ): number => x ); // $ExpectError
}

// The function does not compile if the second argument is a value other than a function...
{
jsonifyKeys( '{beep:"boop"}', true ); // $ExpectError
jsonifyKeys( '{beep:"boop"}', false ); // $ExpectError
jsonifyKeys( '{beep:"boop"}', 5 ); // $ExpectError
jsonifyKeys( '{beep:"boop"}', [] ); // $ExpectError
jsonifyKeys( '{beep:"boop"}', {} ); // $ExpectError
jsonifyKeys( '{beep:"boop"}', 'baz' ); // $ExpectError
}

// The compiler throws an error if the function is provided an unsupported number of arguments...
{
jsonifyKeys(); // $ExpectError
jsonifyKeys( '{beep:"boop"}', 'baz', 'boz' ); // $ExpectError
}
41 changes: 41 additions & 0 deletions lib/node_modules/@stdlib/utils/jsonify-keys/examples/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @license Apache-2.0
*
* Copyright (c) 2025 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var jsonifyKeys = require( './../lib' );

var out = jsonifyKeys( '{beep:"boop"}' );
console.log( out );
// => {'beep':'boop'}

out = jsonifyKeys( '3.14' );
console.log( out );
// => 3.14

out = jsonifyKeys( 'true' );
console.log( out );
// => true

out = jsonifyKeys( 'null' );
console.log( out );
// => null

out = jsonifyKeys( '{ beep: "boop }' );

Check failure on line 39 in lib/node_modules/@stdlib/utils/jsonify-keys/examples/index.js

View workflow job for this annotation

GitHub Actions / Lint Changed Files

Displayed return value is `true`, but expected `false` instead
console.log( out instanceof Error );
// => true
Loading
Loading