My file data.json contains a json object like:
{ "k": : "..some object...", "a": [ "...", "bbb" ] }
In Node I am able to do:
let data = require("./data.json");
and get the whole object in the json file into the variable data.
How do I achieve the same in the Chrome browser?
Assuming you are fetching the json file from the server:
fetch(urlOfJsonFile)
.then(function(response)
{
return response.json();
})
.then(function(data)
{
//Use data as javascript object
})
Related
I have a JSON file which has this:
[
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
]
As you can see it doesn´t have any parent root name. How can I read this JSON with JavaScript ?
I was thinking to PARSE the Json but JSON.parse(need the name)
Is it possible to call this JSON in my JavaScript code and asign it a variable ?
var newSelling = data from the JSON
The JSON is being generated by another system which generates it that way so I need to read the JSON to get the data needed for other processes
the JSON is automatically generated and it is in an external file
So it is a JSON file. Request it with fetch or XMLHttpRequest and access the JSON.
fetch('/path/to/your/file.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
If you want to read the file in the Browser from your local you can use one of these solutions :
Fetch API.
Axios.
XMLHttpRequest.
I recommend Fetch API.
fetch("data.json")
.then(response => response.json())
.then(json => console.log(json));
It works in Firefox, but in Chrome you have to customize security setting.
If you look carefully, you'll see that this JSON file is just a JSON array with only one Object inside of it. So you have to access the object that is in the array.
let arr = JSON.parse(*the json object*);
let obj = arr[0];
I haven't tested this, but hopefully this helps.
Here in your case, using JSON.parse only is not working
but the combination of JSON.stringify and JSON.parse is working as I tried.
So first, we can stringify it and then we can parse it
Like this :
var a = [
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
];
var b = JSON.stringify(a);
var c = JSON.parse(b);
console.log(c[0].id); //output : 1
Parsing JSON should work as follows:
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
More info
Edit:
You can red this question. I think it may help
I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.
(Example of my test file, being the columns A and B respectively):
Johny Wilson | jonhny#email.com
Andrew Jehnsen | andrew#example.com
Billy Soon | billy#mail.com
In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:
var xlsx = require('node-xlsx');
router.post('/enviar', upload.single("lista"),(req, res, next) =>{
//dir is the path of the xlsx file
const workSheetsFromFile = xlsx.parse(dir);
res.send(workSheetsFromFile);
});
returns an object that looks like this:
[
{
"name": "Hoja1",
"data": [
[
"Johny Wilson",
"jonhny#email.com"
],
[
"Andrew Jehnsen",
"andrew#example.com"
],
[
"Billy Soon",
"billy#mail.com"
]
]
}
]
As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.
I've already tried to loop on the data array with:
workSheetsFromFile.data.forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile[data].forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile['data'].forEach((element) =>{
console.log(element);
});
but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(
For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.
What you have here seems to be an array of objects, not an object itself!
try
workSheetsFromFile[0].data.forEach((element) => {
console.log(element);
});
If you have more elements, consider first looping the array and then extracting data
const structuredData = workSheetsFromFile[0].data.map(res => {
return res
});
workSheetsFromFile.forEach(sheet => {
//access data
console.log(sheet.data)
//or
sheet.data.forEach(data => {
//access each data
console.log(data)
})
})
I'm trying to push names in a json file. I'm trying to do something like:
socket.on('create json', function(data){
var data = JSON.stringify(Data, null, 2);
fs.writeFile('participants.json', data)
console.log(data);
});
This is only outputting the data that I've send and results in:
{
"type": "Buffer",
"data": [34,69,120,97,109,112,108,101,32,110,97,109,101, 34 ]
}
When I'm writing the file it deletes everything and puts that in.
I'm looking for a way to write:
{
"names":["name1", "name2", "name3"]
}
Any ideas on how to fix and write this?
Help is very much appreciated!
you have to again read your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs')
fs.readFile('participants.json', function (err, data) {
var json = JSON.parse(data);
json.name = ["name1", "name2", "name3"];
fs.writeFile("results.json", JSON.stringify(json))
})
I'm trying to retrieve data from an API with the following JSON output and I have a function in react that I call.
I can see the api output in console.log(users) so the data is being passed into the function.
I am trying to output the array contained in "data" but can't seem to access the data.
{
"dataCount": 2,
"data": [
{
"name": "Test review header",
"text": "This is adescription for a test review",
"img": "http://pngimg.com/upload/pigeon_PNG3423.png"
},
{
"name": "Test review header2",
"text": "This is adescription for a test review2",
"img": "http://pngimg.com/upload/pigeon_PNG3422.png"
}
]
}
renderUsers() {
const { users } = this.props;
console.log(users);
Object.keys(users).map(name => users[name])
console.log(users[name]);
};
The data you need to iterate over is present in the data field of users.
When you are using lists you have to specify the key property, to make react keep track of each item in list.
renderUsers() {
const { users } = this.props;
return (
<ul>
{
users.data.map(name => {
<li key={name}>users[name]</li>
})
}
</ul>
)
}
First of all, I don't use react but what you want should be the same in other javascript frameworks.
Are you sure that it is JSON you receive?
We need to be sure that you receive a JSON object and not normal text. Lets say you have a function parseResponse(data). We can call JSON.parse(data) to parse the data param to a json object. It is also possible that you store the result in a variable.
Using the JSON object
When we are sure you have the param parsed to a JSON object, we get it's data. For example, if you want to get the name of the first object in data, you can call:
parsedJson.data[0].name
where parsedJson is the result of JSON.parse(data),
data is an array of objects in the JSON,
0 is the first object in the array
It is possible that you have this kind of function then:
function parseResponse(data) {
var parsedJson = JSON.parse(data);
for(var i = 0; i < parsedJson.data.length; i++) {
console.log(parsedJson.data[i].name);
}
}
see jsfiddle
I have an object:
var obj = { "stuff": "stuff" }
In Express, I send it the client like so:
res.json(obj);
Is there a way to configure the response object to automatically add attributes to the json it generates? For example, to output:
{
"status": "ok",
"data": { "stuff": "stuff" }
}
Thanks!
Once the data has been added to the stream, that's too late to rewrap it, so you have to do it before.
Either simply with a function:
res.json(wrap(obj));
You could also add your own json method
express.response.wrap_json = function(obj) {
this.json(wrap(obj));
};
so you can now call
res.wrap_json(obj);
Or you could replace express json implementation with yours
var original = express.response.json;
express.response.json = function(obj) {
original.call(this, wrap(obj));
};
I would only use the last one if you want to override all json calls.