I want to parse this JSON data to a file like this :
JSON
{
"nodes": [
{"id": 1, "name" : "a", "radius" :0.5, "angle" : 2.64159265359},
{"id": 2, "name" : "b", "radius" : 0.6, "angle" : 3.64159265359}
],
"links": [
{"source": "a", "target": "b", "delay": "10ms"}
]
}
File :
[nodes]
a: _ radius=0.5 angle=2.64159265359
b: _ radius=0.6 angle=3.64159265359
[links]
a:b delay=10ms
So far my code is just reading the JSON file
const fs = require('fs');
data = JSON.parse(fs.readFileSync("topo.json","utf-8"));
for (node in data)
{
for (link in data[node])
{
console.log(data[node][link]);
}
}
How can I get those values saved and create a new file having those values in them ?
You did not specify what file type you want to use, so I went with a simple .txt file.
The only small Issue with the code posted, is that these are arrays, so you have to loop a bit differently over them. Apart from that simply write the data into placeholders in your format string and append it to a global object that will be written to the file. Then you should be good to like that:
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('topo.json','utf-8'));
let textFileContent = '';
textFileContent += '[nodes]\n';
data.nodes.forEach(node => {
textFileContent += `${node.name}: _ radius=${node.radius} angle=${node.angle}\n`;
});
textFileContent += '[links]\n';
data.links.forEach(link => {
textFileContent += `${link.source}:${link.target} delay=${link.delay}\n`;
});
fs.writeFile('parsed.txt', textFileContent, function(err) {
if(err) {
return console.log(err);
}
});
Note that this could probably be done more elegant and it won`t scale very well, if your JSON is more complex, than whats shown in the sample...
Related
I'm trying to auto-generate a JSON object for creating a dynamic interactive list message that will be sent to users on WhatsApp.
I need a JSON object in following format:
"sections": [
{
"title": "Main Title",
"rows": [
{
"title": "row 1 title",
},
{
"title": "row 2 title",
}
]
}
]
The above code will generate a list like this
But I don't want to hard code the row's title part {"title": "row 1 title",},{"title": "row 2 title", } .
I tried using the below method where I fetch the title value from an array and merge it using spread syntax but it only returns undefined and doesn't combine all the objects.
method.js
async function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
let data1, data2, d = {}
let i = 0
while (i < arr.length) {
data1 = JSON.parse(`{"title": "${arr[i]}"}`)
data2 = JSON.parse(`{"title": "${arr[i + 1]}"}`)
i++
d = { ...data1, ...data2 }
}
console.log(d)
catch (e) {
console.log(e)
}
}
genJSON()
OUTPUT:
Interactive List message: https://developers.facebook.com/docs/whatsapp/guides/interactive-messages/
How can I achieve the following output {"title": "row 1",},{"title": "row 2", ..} ? Any help or advice is appreciated.
There were two issues with your code:
You were trying to merge two dictionaries with the same keys, hence the previous key gets overwritten. Instead, you should use a JSON Array and append to it.
data2 will be undefined when i = arr.length - 1
I've fixed both the errors in the below code snippet
function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
try {
let d = []
for (const row of arr) {
d.push({
title: row
})
}
console.log(d)
} catch (e) {
console.log(e)
}
}
genJSON()
This is a bit complicated but I am sure a stackoverflow coding genius will grasp easily (kudos from a noob). I have a source.json file, and a changes.json file. In the changes file, I have CRUD type directives where I update, create, delete, etc. This is for a command line tool in node I am building.
To update a playlist entry, I will have to match the payload.id in the changes to the playlist.id in the original file... and then I am assuming delete.json() the original entry and mutate the change. For clarity, I only need assistance with the update part. Not sure how to match id's across the source and changes. I am guessing .filter(), or .reduce()?
source.json:
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8",
"32"
]
}
]
changes.json:
"playlists": [{
"action": "update",
"payload": [{
"id": "1",
"owner_id": "2",
"song_ids": [
"8"
]
}]
}
desired output write to output.json
"playlists" : [
{
"id" : "1",
"owner_id" : "2",
"song_ids" : [
"8"
]
}
]
My code so far which works great, but don't know how to match the id from the source (playlist.id) to the change (payload.id) and if a match, delete the record from the souce and replace with my change record. I think it will need to be just a subroutine in the update part of the if clause and then a .push(). Thanks everyone!
// Stream in source file
const data = JSON.parse(fs.readFileSync('./' + inputFile));
// Stream in changes file
const changes = JSON.parse(fs.readFileSync('./' + changesFile));
for(const [table, actions] of Object.entries(changes)) {
console.log([table]);
if(!(table in data))continue;
// iterate through inner CRUD directives and mutate payloads
for(const actionDetail of actions) {
if(actionDetail.action === 'create') {
console.log('This is a CREATE entry');
data[table].push(...actionDetail.payload);
}
if(actionDetail.action === 'delete') {
console.log('This is a DELETE entry');
}
if(actionDetail.action === 'update') {
console.log('This is a UPDATE entry');
// const something = (is (source)payload.id === (changes)playlist.id) {
// if so, delete source entry and push new entry
// data[table].push(...actionDetail.payload);
//}
}
}
}
fs.writeFileSync('output.json', JSON.stringify(data, null, 2));
If I understand correctly your dataset and applying the fact that you want to mutate your initial data object, you could something like:
console.log('This is a UPDATE entry');
actionDetail.payload.forEach((payload) => {
const index = data.playlists.findIndex(
(playlist) => playlist.id === payload.id
);
if (index > -1) data.playlists[index] = payload;
});
im trying to go from this:
{
"Level":"A",
"Group LVL2":{
"Level":"B",
"Group LVL3":{
"Level":"C"
}}}
To This
{
"Level":"C",
"Group LVL2":{
"Level":"C",
"Group LVL3":{
"Level":"C"
}}}
So i basically want to replace all values of a json key to be the same.
This a part of the code im using:
const fs = require('fs');
const fileName = './' + (Profile) + ".json";
const file = require(fileName);
const key = (Root);
file[Root] = (Value);
fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(error) {
if (error) return console.log(error);
But it only replaces the Level Value of the first json group/line:
{
"Level":"THIS WILL BE REPLACED",
"Group LVL2":{
"Level":"THIS WILL NOT BE REPLACED",
"Group LVL3":{
"Level":"THIS WILL NOT BE REPLACED"
}
}
}
Hope i can find a solution to this, i count on you!
(There doesn't seem to be any beginner friendly solution online)
Below is the general solution for this kind of problem, maybe you can make it more efficient depending on your problem.
It loops through all keys of the object that are nested objects themselves, recurses for each object in the json and updates the "Level" key.
function replaceValues(obj) {
if(obj.hasOwnProperty(key))
obj[key] = value;
for (let property of Object.keys(obj)) {
if (typeof(obj[property]) === "object") {
replaceValues(obj[property]);
}
}
}
Tested on the data you provided with Value = "D"
{
"Level": "D",
"Group LVL2": {
"Level": "D",
"Group LVL3": {
"Level": "D"
}
}
}
I am new in nodejs. I want below result but it shows last value.
"child_skills" : [
"Nodejs",
"Android",
"Javascript"
],
My nodejs method
export function create(req, res) {
return JobCategories.create(req.body)
.then((JobCategoryInstance) => {
var childskill = [];
for (var i = 0; i < JobCategoryInstance.child_categories.length; i++) {
childskill = JobCategoryInstance.child_categories[i].child_categoryname;
}
EngineerSkills.create({ skill_name: JobCategoryInstance.category_name, child_skills: childskill });
return JobCategoryInstance;
})
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
My result is below. Why this is get only last value?
{
"_id" : ObjectId("58c2d5019caa49199854872e"),
"skill_name" : "soft",
"date_updated" : ISODate("2017-03-10T16:32:01.437Z"),
"child_skills" : [
"Javascript"
],
"__v" : 0
}
Instead of adding elements to the array, you are substituting the array with one of the elements every time.
Change this:
childskill = JobCategoryInstance.child_categories[i].child_categoryname;
to this:
childskill.push(JobCategoryInstance.child_categories[i].child_categoryname);
if you want new elements to be added to the array every time.
i have a separate JSON array file which i have my data, but according to user inputs i need to change three values in my JSON then do my http request. i'm stuck at assigning the values i get from my users to the pre define JSON array file i have.
example.json
{
"packageName": "example",
"packageType": "example",
"navigationType": "example",
"description":"",
"consoleAccessLimit": [
{
"accessType": "example4",
"accessLimit": 2
},
{
"accessType": "example3",
"accessLimit": 1
},
{
"accessType": "example2",
"accessLimit": 1
}
]}
i need to change accesslimit of example4, accesslimit of example 3 and accesslimit of example 1
my code following
function askme() {
askDetails("Enter example1 Count:", /.+/, function(scount) {
askDetails("Enter example 3 Count:", /.+/, function (acount) {
askDetails("Enter example 2 Count:", /.+/,function (wcount) {
askDetails("Enter example 4 count:",/.+/,function (price) {
var youexample = (require('./example/example.json'));
// how do i assign the values to my example.json
})
})
})
});
}
please help folks thank you
var fs = require('fs');
fs.readFile('data.json',function(err,content){
if(err) throw err;
var parseJson = JSON.parse(content);
//modify json content here
.writeFile('data.json',JSON.stringify(parseJson),function(err){
if(err) throw err;
})
})
You have to read and write file in order to modify your .json file
Your code isn't structured very well. You're asking the user for input that will change the array values of the JSON. You should restructure your code in a way that allows the questions and the JSON array to be more flexible. For example, maybe today you have four values in the array but in a month that might need to change to six values.
for (var x=0; x < youexample.consoleAccessLimit.length; x++) {
askDetails("Enter example"+x+" Count:", /.+/, function(count) {
youexample.consoleAccessLimit[x].accessLimit = count;
}
}
console.log("youexample result: ", youexample)
What I'm doing here is creating a for loop that runs through the length of the consoleAccessLimit array in the youexample JSON.
Each time through the loop, it runs the askDetails function which gets user input and passes the result into the function with the value count. Then we're assigning the value of count to the specific youexample.consoleAccessLimit index corresponding to x.
Since you have three items in the array, the loop will run three times and assign the result of the user input to each of them.
So if the user enters 5 for the first one, then 9, then 2, the result of the JSON will look like this in the end:
{
"packageName": "example",
"packageType": "example",
"navigationType": "example",
"description":"",
"consoleAccessLimit": [
{
"accessType": "example4",
"accessLimit": 5
},
{
"accessType": "example3",
"accessLimit": 9
},
{
"accessType": "example2",
"accessLimit": 2
}
]}
Open your web developer console to see the result of the console.log output.