# Facing - unexpected token u in json at position 0 at test-script, while running collection using newman script or as a library

**URL:** <https://community.postman.com/t/facing-unexpected-token-u-in-json-at-position-0-at-test-script-while-running-collection-using-newman-script-or-as-a-library/50736>\
**Category:** Help Hub\
**Tags:** newman-project\
**Created:** [August 18, 2023, 4:54pm UTC](https://community.postman.com/t/facing-unexpected-token-u-in-json-at-position-0-at-test-script-while-running-collection-using-newman-script-or-as-a-library/50736 "2023-08-18T16:54:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lunar-module-cosmo10](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@lunar-module-cosmo10](https://community.postman.com/u/lunar-module-cosmo10)\
**Post date:** [August 18, 2023, 4:54pm UTC](https://community.postman.com/t/facing-unexpected-token-u-in-json-at-position-0-at-test-script-while-running-collection-using-newman-script-or-as-a-library/50736/1 "2023-08-18T16:54:00Z")

</div>

> **Archived topic — this may be out of date.**  
> Newman has been replaced by the **[Postman CLI](https://learning.postman.com/docs/postman-cli/postman-cli-overview/)**, Postman’s official, signed command-line tool. It runs collections as Newman did, and also lints API specs, runs mocks and monitors, and syncs local files with Postman from your terminal, CI/CD pipeline or coding agent.  
> Working with an AI coding agent? The [Postman plugin](https://github.com/postmanlabs/postman-plugin) lets agents in Claude Code, Cursor, Codex and others design, mock, test and ship APIs with Postman.  
> For current help, see the [Postman docs](https://learning.postman.com/docs/), try the free [Postman tools](https://www.postman.com/tools) (no account needed), or join us on [Discord](https://discord.gg/58aNNsRBGR).

I am trying to my API collection using newman as a library. Based on reference link below, i have created script (please find below snippet for the same) and trying to run my collection outside postman.

Reference Link : [https://medium.com/apis-with-valentine/postman-how-to-write-files-to-disk-5ee398624a42](https://medium.com/apis-with-valentine/postman-how-to-write-files-to-disk-5ee398624a42)

Code Snippet:

```auto
const newman = require('newman'),
fs = require('fs');

newman.run({
    collection: require('./postman_collection.json'),
	insecure: true,
	globals: require('./globals.json'),
	iterationData: require('./InputData.json'),
	folder: 'TC05',
    reporters: 'cli'
}).on('beforeRequest', function (error, args) {
    if (error) {
        console.error(error);
    } else {
        fs.writeFile(`./writeToFile/${args.item.name}-request.json`, args.request.body.raw, function (error) {
            if (error) { 
                console.error(error); 
            }
        });    
    }
}).on('request', function (error, args) {
    if (error) {
        console.error(error);
    }
    else {
		if(`${args.item.name}` == `genLetter`){
			fs.writeFile(`./writeToFile/${args.item.name}-response.docx`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
			});
		}
		else{
        fs.writeFile(`./writeToFile/${args.item.name}-response.json`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
        });        
    }
}
});

```

During run i see some / few of tests passed with scripts assertions written but for most of API requests its failing due to below error. Please find below snippet for errors.

![image](https://us1.discourse-cdn.com/getpostman/original/3X/c/3/c361cc8f860a36f6b68100a550c6175c6f1f2dd1.png)

 ![image](https://us1.discourse-cdn.com/getpostman/original/3X/e/0/e0dc61b759128f1d7dfaad7e12d1bdb05b161fbc.png)

On the other hand - i have also run my collection using newman cli commands (like using - g for globals, -d for data etc.) and all API steps in collection were passed. But i am using script approach because i wanted to save request and response for each API test step in my collection.

Can any one guide me in right direction on how i can overcome on this issue as i am consistently facing the issue as captured.

---

<div class="post-metadata">

**Author:** ![kevinc-postman](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/kevinc-postman/32/12774_2.png) [@kevinc-postman](https://community.postman.com/u/kevinc-postman)\
**Post date:** [August 21, 2023, 9:37pm UTC](https://community.postman.com/t/facing-unexpected-token-u-in-json-at-position-0-at-test-script-while-running-collection-using-newman-script-or-as-a-library/50736/2 "2023-08-21T21:37:15Z")

</div>

Hi @lunar-module-cosmo10 !

So it seems like the issue that you’re facing could be related to the way you’re handling the requests and responses within the newman events.

The error `"Unexpected token u in json at position 0"` suggests you’re trying to parse `undefined` as JSON in your test or script. This usually happens when the API response isn’t JSON, is empty, or if Postman variables aren’t resolving correctly.

Steps to Resolve:

1. **Log the Response** : Before parsing, print the response to understand its content:

```js
console.log(pm.response.text());

```

2. **Safe JSON Parsing** : Before parsing, ensure the response is valid JSON:

```js
let responseBody = pm.response.text();
if (responseBody && responseBody !== 'undefined') {
    let jsonData = JSON.parse(responseBody);
}

```

3. **Check Endpoint Behavior** : Ensure your API is supposed to return JSON. A 200 status code doesn’t always guarantee a JSON response.
4. **Inspect Scripts** : Check both pre-request and test script sections in Postman for outdated or conflicting scripts.
5. **Content-Type Header** : Ensure the API’s response header includes `Content-Type: application/json` if you’re expecting JSON.

Hope this helps! 🙂

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [November 19, 2023, 9:37pm UTC](https://community.postman.com/t/facing-unexpected-token-u-in-json-at-position-0-at-test-script-while-running-collection-using-newman-script-or-as-a-library/50736/3 "2023-11-19T21:37:40Z")

</div>

Closed on November 19, 2023, 9:37pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
