简体   繁体   中英

How to convert a JSON data read from a file as JSON object

I want to pass a JSON object which is read from a file to a POST api. However, I am seeing that when it is read from the file then it is not working. However when the hardcoded JSON data is passed it is working. To make you understand better, I am giving the below code example :

var json_content = {};
fs.readfile(file, function(err, data) {
        json_content = data;
        console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);
        if(err) {
            console.log("file reading error is = "+err);
            return;
        }
}

The output of the above console.log statement is below :

typeof json_variable= object| json_content = {'title' : 'adventure', 'name': 'Homes'}

When I am sending this above json_content to my post call as a body using superagent, it is not working. In fact in the server it is received as undefined if I do req.body.title

However instead of above mechanism wherein I am reading it from a file and sending, if I set the json_content variable a hardcoded value, then it is working fine. Below is the code and output :

json_content = {'title' : 'adventure', 'name': 'Homes'};
console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);

The output is different this time as below :

typeof json_variable = object |json_content =[object Object]

Please notice the difference in the output as the json_content is now printed as [object Object] unlike earlier case where it was printing the whole JSON.

Could you please suggest, how do I need to change the first approach when I am reading it from a file and sending it to post to get the similar kind of effect which I am getting while hard coding the json ?

The only difference between them is that one is a string representation of object while second one is javascript object.

 var json_content = '[{"key":"value"}]'; console.log("json_content"+json_content); var json_content = [{"key":"value"}]; console.log("json_content"+json_content); 

One more thing is happening in your code is that you are using concatenation + in your console.log() statements.
To me you should avoid using such way and try with , instead:

 var json_content = '[{"key":"value"}]'; console.log("json_content", json_content); var json_content = [{"key":"value"}]; console.log("json_content", json_content); 

For your last comment:

 var json_content = '[{"key":"value"}]'; json_content = JSON.parse('[{"key":"value"}]'); console.log("json_content"+json_content); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM