why does my JSON file contain [object Object]? - javascript

I am using sqlite3 and nodeJS, and querying a database. I want to copy the queries into a json file. I run into problems with the json file having strings and objects. Why does my JSON file contain:
[object Object]
Here is my code:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}rows.forEach((row) => {
arr_string = JSON.parse(JSON.stringify(row));
fs.writeFile("tempo.json", arr_string, function(err){
});
console.log(arr_string);
});
});
I would like to eventually use ajax requests for these entries.

arr_string = JSON.parse(JSON.stringify(row));
//^---------^--- This is parsing the string back to a new object.
You are parsing the stringified item to a new Object, hence the node.js file writer is trying to write the object to the write stream, resulting in interpreting it as [object Object].
Just omit the JSON.parse, so that the stream will effectively be a string instance:
arr_string = JSON.stringify(row);
Additionally, you should aggregate the result and write it only one time, or append to the file:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}
let _strings = [];
const newline_separator = ''; // <-- use whatever separator you need.
rows.forEach((row) => {
arr_string = JSON.stringify(row);
console.log(arr_string);
_strings.push(arr_string);
});
fs.writeFile("tempo.json", _strings.join(newline_separator), function(err){});
});
Since it's a json, I would suggest you to provide us a more precise input, so that we can guess what the expected result is.

I think while storing JSON data into SQLite, you're not stringifying it. If you directly store JSON data into SQLite it'll store like [object Object] format. My suggestion is to stringify the data while storing in SQLite. And while retrieving only parse it. Then your problem will solve.

arr_string is actually not a string, as you JSON.parse d it. Remove the JSON.parse call.

The JSON.stringify() method converts a JavaScript value to a JSON string
arr_string = JSON.stringify(row);
"the problem now with doing that is now the JSON file only writes the last row (and i queried 4) and also I cannot call arr_string.caphi because its not an object anymore"
Create an empty array(list) and push each result of query in array.And then
finally convert it into JSON.
sample code :
var rows=[{"holla":"bolla"},{"holla":"bolla1"}];
console.log(JSON.stringify(rows));

JSON.stringify() takes JSON object and returns String
JSON.parse() takes String and returns JSON object
try :
rows.forEach((row) => {
arr_string = JSON.stringify(row); // 'row' data is converted to String
fs.writeFile("tempo.json", arr_string, function(err){
});`

Related

Parsing Json data from a file

I am building a Node JS application that reads file that contains array of Json objects, and displays it on a table. I need to parse the JSON data array.
sample json data:
[{"name":"Ken", "Age":"25"},{"name":"Pulsar", "Age":30}]
I have used the following to read from file and pass it into another json object:
const fileRead = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", (err, data)=>{
console.log(JSON.parse(data))
return JSON.parse(data);
});
console.log(fileRead)
The expected output is array of JSON objects. However, when I console.log the fileRead, I do not get intended output:output
I further intend to iterate through the data read above and pass it to a JSON object:
const data = {headers:["Name", "Age"], rows: fileRead.foreach((row)=>{return row.name, row.age];})}
Please check and advise.
const fs = require('fs');
// Thanks to: https://nodejs.dev/learn/reading-files-with-nodejs
try {
const data = fs.readFileSync('test.txt', 'utf8');
console.log(data);
const json = JSON.parse(data);
console.log(json);
} catch (err) {
console.error(err);
}
the issue was with encoding. I passed utf-8 to filereadsync as second parameter, and it worked.
Thank you
If I do your task, I'll save data on a table, then I'll paste data to a json file and I'll read the file like your code.
I do that because I want to control the format of the JSON file. If you save a manual file in JSON, there are many ways you have problems with formatting JSON.
I hope my answer is helpful. Good luck!
 

Fetch returning undefined after parsing with json

I am writing a JavaScipt application and am attempting to fetch data from a certain URL but am getting an undefined value. The expected value after fetching and converting it to json should result in an array. I am not sure why this is happening. I have put my code below:
let promiseResponse = fetch("some-url");
let response = await promiseResponse;
// check if there was an error in fetching the data (no error detected)
if(!response.ok) {
alert("An error occured when attempting to fetch data.")
}
// a console.log statement here for the var 'response' results in "[object Promise]"
let parsedPromiseResonse = response.json();
let parsedResponse = await parsedPromiseResonse;
// printing out the 'parsedResponse' var gives me [object Object]
// printing out the 'parsedResponse[0]' var gives me undefined
EDIT:
For more context, the data to be retrieved in the URL is formatted like this:
{"variants":["some-string","some-string"]}
Any help would be greatly appreciated!
To access the json to have to call the entity variants then access to the items, something like
alert(parsedResponse.variants[0])
And the result should be
some-string
If you are referring to the varients array, then this is how you will get the array values.
parsedResponse["varients"]
For the first index
parsedResponse["varients"][0]

Turning JSON.parse() return type to an array of object

I have defined a file called note-data.json which contains json data. In the following code a variable of type of array called notes is declared. What I want to achieve is that the program read the json file save it in the noteString variable and then make a array of object with JSON.parse() from noteString and put it into notes array. So I can add new objects to the json file. But when the programme gets to the line note.push() it complains since, I think, the type of notes has turned to a string and push is not define for string. How can I get around this issue?
Please ignore the fact that if the json file is not provided the the program crashes.
My code:
const addNote = (title, body) => {
let notes= [];
const note = {
title,
body
};
const notesString = fs.readFileSync('node-data.json', 'utf8');
notes = JSON.parse(notesString);
notes.push(note);
fs.writeFileSync('node-data.json', JSON.stringify(note));
}
File note-data.json:
{"title":"Greeting","body":"Hello"}
I think you are fumbling with your variables here. From what I understood - you want to read JSON from a file and append that JSON to an array, right? Following code will help you do just that
const addNote = (title, body) => {
let notes= []; //Declare an array
const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
notes.push(note); //Append new JSON to your array
//This line below appears to have no purpose ??
fs.writeFileSync('node-data.json', JSON.stringify(note));
}

What's the best way to split up a JSON formatted string from DynamoDB in Javascript

I am creating a project in AWS Lambda using JavaScript and I am receiving data from a DynamoDB table in JSON format which i am then converting to a string. I need to find the easiest way to split up this string so each column from the database has it's own value saved in it's own string variable.
Here's an example of my code:
function readDynamoItem(params, callback) {
var AWS = require('aws-sdk');
AWS.config.update({region: AWSregion});
var dynamodb = new AWS.DynamoDB();
console.log('reading item from DynamoDB table');
dynamodb.scan(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else{
console.log(data); // successful response
callback(JSON.stringify(data));
}
});
}
The response for callback would result in:
{\"Items\":[{\"id\":{\"S\":\"5\"},\"message\":{\"S\":\"hello\"}}],\"Count\":1,\"ScannedCount\":6}
So in this case i would need a string called id containing "5" and a string called message containing "hello". I have looked into using the .split() function but I'm not sure how I would just get the string without all the {\"S\":\" etc. part
Any help would be greatly appreciated
Your data varaible already holds an object. Passing that to callback w/o stringifying it is the proper way. With that callback you can easily addres the ID field like this:
var id = data.Items[0].id;
var message = data.Items[0].message
You may add some logic regarding the effectiv number of items in the array.
I think you should keep the data as JSON not string, and then:
var myObj;
var items = data.Items;
for(var key in items) {
myObj[key] = items[key];
}

Parse serialized Laravel cache data with Javascript

I'm using Laravel's cache feature to store keys in Redis. The key is stored as an array which Laravel's cache automatically serializes and unserializes into something like this:
"s:18:\"[\"bob\",\"dave\"]\";"
In PHP Laravel handles the parsing, but I need to access the data from Javascript. I am using the ioredis package in node. Everything works fine except for unserializing the data.
var Redis = require('ioredis');
var rediscache = new Redis();
rediscache.get("mykey", function (err, result) {
//Attempt to parse?
result = JSON.parse(result);
}
The key is fetched correctly, but is stuck as a string. I tried JSON.parse but this throws an error, I suppose because the format is wrong.
Unexpected token s at Object.parse (native)
How can it be correctly unserialised? I ideally want to get it as a Javascript array so a value can be altered, then re-serialised and saved back to Redis.
Many thanks.
What you have is a serialized string which contains a JSON string.
You can use a library if you don't want to write it yourself: https://github.com/naholyr/js-php-unserialize
After that, you'll have a JSON string, which you can then parse.

Categories

Resources