Bryce Bryce - 1 year ago 62
Javascript Question

Unexpected string when outputting textfile

I have some data I'm trying to output to an output text file. This is how I am trying to do that:

'use strict';
var fs = require('fs');

let id = require('./ID.json');
let obj = require('./dataOut.json');
let isp = require('./isp');
let dst = require('./dst');
let dst_lat = require('./dst_lat');
let dst_lng = require('./dst_lng');

const output = [];
let i = 0;

obj.forEach(block => {
let outputOut =
' {\n',
' "_id": ' + '"' + id[i] + '",\n',
' "latlng": [\n',
' ' + dst_lat[i] + ',\n',
' ' + dst_lng[i] + '\n',
' ],\n',
' "name":' + '"' + isp[i] + '",\n',
' "address":' + '"' + dst[i] + '"\n',

I want the data to look exactly how it appears in the variable outputOut, however, when I run this code I run into the error unexpected string.

I understand why I'm running into this error, but I cannot think of a way to resolve it.

How can I save my outputOut data to a textfile?

Answer Source

You may be misunderstanding JSON.stringify. It takes a javascript object or a valid JSON object and returns the string version of that. Your string concatenation is unnecessary. Secondly, you're actually concatenating outputOut. Concatenation in done like so: var saying = "Hello" + "World";

Try building an object instead:

'use strict';
const fs = require('fs');

const id = require('./ID.json');
const obj = require('./dataOut.json');
const isp = require('./isp');
const dst = require('./dst');
const dst_lat = require('./dst_lat');
const dst_lng = require('./dst_lng');

const output = [];
let i = 0;

obj.forEach(block => {
    let outputOut = {
      "_id": id[i],
      "latlng": [
      "name": isp[i],
      "address": dst[i],


fs.writeFile('./output.json', JSON.stringify(output, null, 2), 'utf-8');

This approach is much more idiomatic and simpler. Additionally it's easier to read. Let JavaScript do the heavy lifting for you, rather than writing complex code which still may achieve the same results but at a much higher cost.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download