I'm trying to work with a json file but I can't figure out how to read just a specific object from a json file.
My current code looks like this:
try {
const data = fs.readFileSync("addresses.json", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
This works fine. However when I try to get some object from the file like this:
console.log(data.address)
It doesn't work because it is a string.
So my question is how can I read just a single object from the json file.
Thanks a lot!
Try:
const parsedData = JSON.parse(data)
const address = parsedData.address
You need to use JSON.parse(), as right now, you are trying to access a property off of a string. However, the method will change it to an object.
// Dummy JSON data
const data = `{ "address": "Stack Overflow" }`;
const json = JSON.parse(data);
console.log(json.address);
This will make it possible to access the properties off of the object.
you must convert the data into json like so:
JSON.parse(data)
In your example :
try {
const data = fs.readFileSync("addresses.json", "utf8");
console.log(JSON.parse(data).address);
} catch (err) {
console.error(err);
}
I hope I answered your question.
Feel free to comment if I misunderstood you or you have some questions ;)
Related
I am trying to get form data to json object and modify it... But it is not working...
Here is my code-
let formData = new FormData(thisForm).entries();
let body = JSON.stringify(Object.fromEntries(formData));
console.log(body);
console.log(body.firstName);
console.log("service=" + body.service);
body.service = "hello";
the console.log(body) is printing output like this-
{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}
But console.log(body.firstName); is printing undefined.
Same thing is happening for other things.. What is the problem?
It's because body is a string, not a JSON object, because you've JSON.stringify'd it.
Use JSON.parse instead to create a JSON object that you can edit like that.
var body = '{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}';
var jsonBody = JSON.parse(body);
console.log(jsonBody.firstName);
Because you use JSON.stringify() on the object first.
You use that to transfer the object over http. Apply that later on and you're fine.
I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)
I have a JSON that looks like this:
{"marker":[{"#attributes":{"start":"Im Berge",
"finish":"Eichelberger Stra\u00dfe"
...
I am trying to parse the attributes inside the "#attributes", but have not found a way to do it. What I tried so far:
const fs = require('fs');
var jsonObj = JSON.parse(fs.readFileSync('route1.json', 'utf8'));
console.log(jsonObj['#attributes']);
Also tried the same with
console.log(jsonObj.marker['#attributes']);
Neither of which work. I understand that this is supposed to be a json-ld and that I'm supposed to parse an object with an "#" sign with ['#attributes'], but either way I always get an error or undefined. I got the JSON from an API I wanna use and it is in there multiple times, so I have no way around it.
.marker is an array so:
console.log(jsonObj.marker[0]['#attributes']);
But you may want to loop through it:
jsonObj.marker.forEach(marker => console.log(marker['#attributes']));
You can require a JSON file, instead of JSON.parse & fs.readFileSync
var jsonObj = require('./route1.json');
I have a .json file where i have people's names stored. I'm reading the content from this file using the file system from Node Manager and then I'm trying to convert this json to string and parsing it to JS object. After parsing it to JS object i get as type string instead of object.
Here is the example json file :
{
"21154535154122752": {
"username": "Stanislav",
"discriminator": "0001",
"id": "21154535154122752",
"avatar": "043bc3d9f7c2655ea2e3bf029b19fa5f",
"shared_servers": [
"Reactiflux",
"Discord Testers",
"Official Fortnite",
"Discord API"
]
}
}
and here is the code for processing the data:
const string_data = JSON.stringify(fs.readFileSync('data/users.json', 'utf8'));
const data = JSON.parse(string_data);
console.log(typeof(data)); // <-- this line here shows the type of data as string
const results_array = Object.values(data);
where fs is the file system package from npm.
don't use JSON.stringify as it is further changing the string representation of JSON object. An example of what is happening is below
Imagine if you have a data in your file as shown below
{
"key": "value"
}
When you read the file (using readFileSync) and apply JSON.stringify, it is converted to a new string as shown below. You can notice that the double quotes are now escaped
"{\"key\": \"value\"}"
Now when you will parse it using JSON.parse then instead of getting the desired object, you are going to get back the same string you read from the file.
You are basically first performing and then undoing the stringify operation
Okay so fs.readFileSync returns a string so you dont need to use stringify
var fs = require('fs');
var read = fs.readFileSync('data/users.json', 'utf8');
console.log(read);
console.log(typeof(read));
const data = JSON.parse(read);
console.log(typeof(data));
You will see it returns an object
This works for me:
const data = JSON.parse(fs.readFileSync('data/users.json', 'utf8'));
console.log(typeof(data)); // <-- this line here shows the type of data as OBJECT
const results_array = Object.values(data);
i want parse a json file to Dictionary and want write some data to it.
this is what i have, but i become a empty Dictionary
var users = {};
fs.readFile('login.json', function read(err, data) {
if (err) {
throw err;
}
users = JSON.parse(data);
});
In Node.js you can require JSON files, so your code could simply become:
var users = require('./login.json');
Though note the data will be cached, so if your login.json file changes without an application restart the users object will stay the same.
readFile is an asynchronous function. If you want to do anything with the data in it, you must do so in the callback function (or at some point after you know the callback has been run).
You may want to use readFileSync instead.