Why does express.js generate a JSON.parse error? - json

I installed node.js and express.js and I'm trying to use:
var str = { test: 'info'};
obj = JSON.parse(str);
but it causes an error: SyntaxError: Unexpected token 0 at Object.parse (native)
How can I fix this? Thanks.

you parsing Object to Object?
JSON.parse() expects string:
var str = '{"test": "info"}';
obj = JSON.parse(str);

Basically JSON.parse() expects string but you were passing object, so instead do this:
var original = { test: 'info'};
var str = JSON.stringify(original);
var restored = JSON.parse(str);
Here's helpful docs about JSON https://developer.mozilla.org/en/Using_native_JSON

str is not a string, but an object. Put the whole thing into a string first, i.e.:
var str = '{ "test": "info"}';
obj = JSON.parse(str);

express.js cannot parse JSON objects on its own. Try using the body-parser
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});

If you want to create JSON you need to use JSON.stringify.
var thing = { test: 'info' };
var json = JSON.stringify(thing);
If you want to parse JSON to an object you need to use parse. Parse expects you to use valid JSON.
var json = '{ "test": "info" }'; //Use double quotes for JSON
var thing = JSON.parse(json);
An easy way to test if you are using valid json is to use something like: http://jsonlint.com/

The thing you are calling str is actually already an object. JSON is not necessary, pure JavaScript is all you need:
var obj = { test: 'info'};
console.log( JSON.stringify(obj) ); // JSON output

Related

Parsing JSON in Google Scripts

I am trying to parse a JSON object in Google Scripts but I can't seem to get it to work.
The JSON I am trying to parse looks like this
{
"keywords":[
{
"c":0.015165274822976534,
"monthly":[ ],
"kw":"handstand",
"n":60500,
"sb":0.3
}
],
"not_found":[
]
}
I can't seem to access any of the values within the object. If I use JSON.parse() it seems to create a non-JSON object.
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj);
Returns
{keywords=[{c=0.015165274822976534, monthly=[], kw=handstand, n=60500, sb=0.3}], not_found=[]}
This doesn't validate.
If I try to work with that anyways this happens
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj.keywords.n)
Returns undefined
If I don't use JSON.parse and just work with the original response object I get the following:
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[ ],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
Logger.log(response.keywords);
I get undefined
I'm not really sure where I am going wrong here. Any help is appreciated. Thanks!
As #Tanaike mentions, your n property is a property of an object in the keywords array. So to log the values of n, you need to - after parsing the string to JSON - evaluate each object in keywords:
var response = '{"keywords":[{"c": 0.015165274822976534, "monthly": [ ], "kw": "handstand", "n": 60500, "sb": 0.3}], "not_found": []}'
var obj = JSON.parse(response);
// Log all values of n for each keyword:
obj.keywords.forEach(function (keyword) {
console.log("Word: " + keyword.kw + ", times used: " + keyword.n);
});

How to extract value from json response in postman, whose key has '.' in it

It is pretty straight forward to to get a value of a key from json response in postman say :
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData.value);
});
For JSON Response
{
"value": "task-1405"
}
I am not able to extract json value in the below case where key has a '.' as part of its string.Can any one help me with this.
"result": {
"cluster.moid": "domain-c433242"
}
I tried the following below code:
pm.test("abc", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var moid = result.'cluster.moid' ;
pm.environment.set("clusterMoid", moid);
});
Could figure out to extract value for the above case, The below code works
pm.test("StatusForAddClusterApplyCheck", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var jsonString = JSON.stringify(result).substring(17,31);
pm.environment.set("clusterMoid", jsonString);
});
But only if the string length are constants.
Any other answer in case string length are dynamic?
In javascript (And also in postman), object properties can be accessed with '.' operator or with associative array indexing using []. The same goes for JSON objects.
ie. object.key is equivalent to object["key"].
this should do the trick for you:
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData["cluster.moid"]);
});

Writing JSON object to a JSON file with fs.writeFileSync

I am trying to write a JSON object to a JSON file. The code executes without errors, but instead of the content of the object been written, all that gets written into the JSON file is:
[object Object]
This is the code that actually does the writing:
fs.writeFileSync('../data/phraseFreqs.json', output)
'output' is a JSON object, and the file already exists. Please let me know if more information is required.
You need to stringify the object.
fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
I don't think you should use the synchronous approach, asynchronously writing data to a file is better also stringify the output if it's an object.
Note: If output is a string, then specify the encoding and remember the flag options as well.:
const fs = require('fs');
const content = JSON.stringify(output);
fs.writeFile('/tmp/phraseFreqs.json', content, 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
Added Synchronous method of writing data to a file, but please consider your use case. Asynchronous vs synchronous execution, what does it really mean?
const fs = require('fs');
const content = JSON.stringify(output);
fs.writeFileSync('/tmp/phraseFreqs.json', content);
Make the json human readable by passing a third argument to stringify:
fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));
When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify().
Here is a working example:
var fs = require('fs');
var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);
Hope it could help.
Here's a variation, using the version of fs that uses promises:
const fs = require('fs');
await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default

CSV to JSON using NodeJS

I'd like to convert a CSV file to a JSON object using NodeJS. The problem is that my CSV file is hosted on a special URL.
URL : My CSV here
var fs = require("fs");
var Converter = require("csvtojson").Converter;
var fileStream = fs.createReadStream("myurl");
var converter = new Converter({constructResult:true});
converter.on("end_parsed", function (jsonObj) {
console.log(jsonObj);
});
fileStream.pipe(converter);
Issue :
Error: ENOENT, open 'C:\xampp\htdocs\GestionDettes\http:\www.banque-france.fr\fileadmin\user_upload\banque_de_france\Economie_et_Statistiques\Changes_et_Taux\page3_quot.csv'
at Error (native)
Edit #1 :
Request.get(myurl, function (error, Response, body) {
var converter = new Converter({
constructResult: true,
delimiter: ';'
});
converter.fromString(body,function(err, taux){
console.log(taux); // it works
});
});
I did just that in a module reading and writing on different protocol in different data formats. I used request to get http resources.
If you want take a look at alinex-datastore. With this module it should work like:
const DataStore = require('#alinex/datastore').default;
async function transform() {
const ds = new DataStore('http://any-server.org/my.csv');
await ds.load();
await ds.save('file:/etc/my-app.json');
}
That should do it.

how to post json object in apigee baas using titanium studio

var jsonobj = { "username" : "cat" };
var client=Ti.Ui.createHttpClient({
onload:{ },
onerror : { }
});
client.open('POST',api.usergrid.com/serv-d/demo1/logs);
client.send(jsonobj);
Details:
jsonobj is the json object to be posted in the apigee baas.
client.open has the url for the apigee baas.
client.send sends the json object.
You need to send your data as JSON payload not as url encoded POST fields as it is being sent right now. You just need to set the content-type to json.
var client = Ti.Ui.createHttpClient({
onload:{ },
onerror : { }
});
client.setRequestHeader('content-type', 'JSON');
client.open('POST',api.usergrid.com/serv-d/demo1/logs);
client.send(JSON.stringify(jsonobj));
I think your jsonobj should be:
var jsonobj = {username: uname, password: pass};
Since JSON.stringify() will take care of stringify-ing it.
Let's do some testing with:
var client = Ti.Network.createHTTPClient();
client.open('POST', 'http://requestb.in/1b1yblv1');
client.send(payload);
With:
var payload = {username: "cat"};
At http://requestb.in/1b1yblv1?inspect you see:
username=cat
With:
var payload = JSON.stringify({username: "cat"});
It is:
{"username":"cat"}
So that's what you need right?