how insert " in numbers of my json [NODEJS] - json

i have a JSON like this:
{"name1":123,"name2":123,"name3":123}
i want put "" in numbers To stay like this:
{"name1":"123","name2":"123","name3":"123"}
Anybody know a nodejs code to do this?

Assuming the object is already parsed and stored in a variable somewhere, you can do:
Object.keys(myObject).reduce((o, k) => Object.assign(o, {
[k]: myObject[k].toString()
}), {})

As Judson Terrel was saying above, you should consider using JSON.stringify(myJsonObject)
but if you so desired to use regex, here it is
let str = '{"name1":123,"name2":123,"name3":123}';
let result = str.replace(/\b(\d+)/g, "\"$1\"");
console.log (result);
//console-output => {"name1":"123","name2":"123","name3":"123"}

The simplest way is to parse the JSON string to an object using JSON.parse, and then convert the object values to string with the String function, like this:
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)

Related

How to get certain text from json object value

I am using react js. I have some json data where I am fetching the timestamp. It has date and time both. For example:
timestamp":"2020-03-23T14:00:00.000Z"
Now after fetching all the json data including timestamp. I wanna make a chart, but I only want to use the date in my chart, not the time. How do I only get the date from the timestamp in the form of 2020/03/23 not the- but with /? I am using chartjs for making the chart Thanks.
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate.replace("-", "/"); //here it doesn't replace with `/`
console.log(tempsymbolsDate);
}
You can split the string using "2020-03-23T14:00:00.000Z".split("T")[0] to get the date without the time.
To replace - characters with /, use the str.replace(searchvalue, newvalue) method. For example:
"2020-03-23".replace(/-/g, "/")
Edit:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempsymbolsDate = tempsymbolsDate.replace(/-/g, "/");
console.log(tempsymbolsDate);
}
Edit 2:
for (const dataobj of json) {
let tempsymbolsDate = dataobj.timestamp.split("T")[0];
tempArray = tempsymbolsDate.split("-");
tempsymbolsDate = tempArray[2] + "/" + tempArray[1] + "/" + tempArray[0];
console.log(tempsymbolsDate);
}

how to parse string object without double quote in front in json

i have an array in my angular applicaton for eg:
searchTerm : any[]
I have a textbox with a value {'state':'tn'} and want to push this to the searchTerm array. Currently i add this item to a service and then array as:
private onItemAdded(event): void {
const filter = JSON.parse('"' + event['value'] + '"');
this.dataService.addFilter(filter);
}
But it is storing as "{'state':'tn'}"
How can i parse this without double quotes in the front?
console.log('ADDED FILTER', event['value']);
here the value is printed as {'state':'value'}
but when assign to variable as below, it adds double quotes
let filter = event['value'];
Thanks
why you are using parse?, it is for converting from JSON to object, instead use stringify which will parse your object to JSON(string)
const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing
As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})
You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.

String array to jSON array in Javascript?

I have a string file like this
["ORM.mp4","bla.bla","blaa.blaa"]
an any body tell me how can I convert it to array of jSON object.
I have tried various methods like json.stringify() then json.parse()etc.
None of them worked.
Any help would be highly appreciated!
Use eval https://www.w3schools.com/jsref/jsref_eval.asp
a = eval('["ORM.mp4","bla.bla","blaa.blaa"]')
console.log(a)
var test = '["ORM.mp4","bla.bla","blaa.blaa"]';
var data = JSON.parse(test);
console.log(data );
You can use JSON.parse() for parsing json.
var obj = ["ORM.mp4","bla.bla","blaa.blaa"].reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});

How to read a text file and return it as a JSON object in Node JS?

I have a text file. I need to read the file inside a function and return it as a JSON object. The following is throwing an error "Unexpected token V in JSON at position 0" .
Server.js
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
obj = JSON.parse(data);
console.log(obj);
});
result.txt looks like the following
VO1: 10 5 2
VO2: 5 3 2
I think I cannot use JSON.parse directly. How do I proceed?
Assuming the following:
Every line is separated by a newline character (\n)
Every line is separated by a : where the part in front of it is the key and the part behind it is a (space) separated string that should indicate the keys values as an array.
Below should work for your format:
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
let obj = {};
let splitted = data.toString().split("\n");
for (let i = 0; i<splitted.length; i++) {
let splitLine = splitted[i].split(":");
obj[splitLine[0]] = splitLine[1].trim();
}
console.log(obj);
});
It could be issue with UTF-8 string format, Tried below code and it works
const resultBuffer = fs.readFileSync('result.txt');
const resultData = JSON.parse(resultBuffer.toString().trim());
Thanks to Baao for providing that answer.
As another flavor of solution, if you don't have any ":" for perhaps a list of files you could always code in a key like so:
var data = fs.readFileSync(pathAndFilename);
var testData = {};
var splitList = data.toString().split('\r\n');
for (var i = 0; i < splitList.length; i++) {
testData['fileNumber' + i.toString()] = splitList[i];
}
You need to parse the text file by yourself. You can use RegExp or some other means to extract the values, create an object out of that and then JSON.stringify it.
improving upon #baao answer:
const fs = require("fs")
fs.readFile('.czrc', 'utf8', function (err, data) {
if (err) {
console.error(err)
throw "unable to read .czrc file.";
}
const obj = JSON.parse(data)
});
Your result.txt is not valid json.
Valid json would look like this.
{
"VO1": [10, 5, 2],
"VO2": [5, 3, 2]
}