I have two files data.json and index.js.
data.json looks like this:
{
"stacy": {
"age": 24,
"name": "Stacy",
"properties": [ "crazy", "funny", "straight" ]
},
"john": {
"age": 41,
"name": "John",
"properties": [ "experienced", "direct", "straight" ]
},
}
How can I import data.json into index.js?
I thought about something like this: import * as persons from data.json;
You will find all of your JSON data in the data variable.
By using fetch API you can load JSON data. Code below:
fetch('data.json')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
})
.catch(err => console(err));
try to write the exact file location.
Related
I am trying to iterate through the array of objects but somehow not getting it right. Can somone please let me know where i am going wrong.
Here is the data
const response = {
"pass": 1,
"fail": 2,
"projects_all": [
{
"projects": [
{
"name": "Project1",
"current": null,
"previous": {
"environment": "qa4nc",
"status": "UNKNOWN",
}
}
]
},
{
"projects": [
{
"name": "Project2",
"current": null,
"previous": {
"environment": "qa4nc",
"status": "FAIL",
}
},
{
"name": "Project3",
"status": "LIVE",
"current": null,
"previous": {
"environment": "qa4nc",
"status": "UNKNOWN",
}
}
]
}
]
}
And here is the code i tried
if(response) {
response?.projects_all?.forEach((projects) => {
projects.forEach(project) => {
if(project.previous !== null) {
//do something here
}
});
});
}
I am trying to iterate through this array of objects but it says projects not iterable. Any help is appreciated to make me understand where i am going wrong.
You were missing iterating over an array properly. A good idea is to format the JSON object that you plan to iterate over. So that you can see what are the arrays and objects, and at what hierarchy.
if (response) {
response?.projects_all?.forEach((project) => {
project?.projects?.forEach((project) => {
console.log(project?.name);
});
}
);
}
response?.projects_all?.forEach((projects) => {
This is the exact correct way to start the code. The problem that happens next is you apparently misunderstand what projects means in the following context
You do projects.forEach(project) as if you think projects is as array. projects is not an array at this point, it is an object that looks like this:
{
"projects": [
{
"name": "Project1",
"current": null,
"previous": {
"environment": "qa4nc",
"status": "UNKNOWN",
}
}
]
}
So I would actually want to do projects.projects.forEach(project => { ... }), or you could change the variable name from projects so it makes more sense to read.
First, determine what shape your response object currently has.
By using the ?. operator your essentially muting JS built in error reporting.
From the context, I assume your response actually looks like this:
console.log(response);
{
data: {
projects_all: [ ... ]
}
}
Therefore your existing code using response?.projects_all doesn't actually hit the projects_all property inside your response.
Can you try the following:
response.data.projects_all.forEach((project) => {
console.info("Project: ", project);
project.projects.forEach((project) => {
console.log(project, project?.name);
});
});
Alternatively, if you don't have a data key inside your response object, you can omit it in the loop:
response.data.projects_all.forEach((project) => {
console.info("Project: ", project);
project.projects.forEach((project) => {
console.log(project, project?.name);
});
});
This is my json-server database.
{
"users": {
"sarahedo": {
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
},
}
I need to add new ID in "questions": ["8xf0y6ziyjabvozdd253nd", "am8ehyc8byjqgar0jgpub9"]
but I can't access it in fetch URL.
I tried to check the URL in browser "HTTP://localhost:3000/users/sarahedo"
I get empty object for some reason {}
I want to know how can I add new data to it using fetch POST.
The reason that you get an empty object from http://localhost:3000/users/sarahedo is that you've defined your data in .json file incorrectly. If you correct your .json file with the below data, you'll see your user obj by hitting http://localhost:3000/users/sarahedo in the browser.
{
"users": [
{
"id": "sarahedo",
"name": "Sarah Edo",
"avatarURL": "https://pluralsight.imgix.net/author/lg/6f77d113-ea36-4592-814d-9d4acb32f231.jpg",
"answers": {
"8xf0y6ziyjabvozdd253nd": "optionOne",
"6ni6ok3ym7mf1p33lnez": "optionOne",
"am8ehyc8byjqgar0jgpub9": "optionTwo",
"loxhs1bqm25b708cmbf3g": "optionTwo"
},
"questions": [
"8xf0y6ziyjabvozdd253nd",
"am8ehyc8byjqgar0jgpub9"
]
}
]
}
You can either use below code for adding new data, using fetch POST:
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
return response.json()
}
For more detailed info about fetch POST, check this out: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
I am trying to load/read data from a local json file using JQuery/Javascript. Everything I have tried so far is throwing me CORS policy error. I don't know how to resolve this.
<html>
<body>
<div>
Fetch JSON
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#fetch').click(function() {
$.getJSON('music.json', function(data) {
albums = data['Albums']
console.log(albums)
})
});
})
</script>
</body>
</html>
Json file -
{
"Albums": [{
"albumName": "Desire",
"artist": "Bob Dylan"
},
{
"albumName": "Live in London",
"artist": "Leonard Cohen"
},
{
"albumName": "Abbey Road",
"artist": "The Beatles"
},
{
"albumName": "Blackstar",
"artist": "David Bowie"
}
]
}
How to get this running?
You should run your project on the web server, in this case, you can do this:
data.json
{
"albums": [
{
"name": "First Album",
"artist": "Leonard Cohen"
}
]
}
in html or js file:
fetch('http://127.0.0.1:5500/data.json')
.then(response => response.json())
.then(json => console.log(json))
in this case, my webserver local address is http://127.0.0.1:5500
I'm trying to import JSON file that contains an array of blog-posts. All data contained in JSON file is imported successfully, except the Array of objects (edges)
This code is part of a unit test created with JestJS for a site build with Gatsby.
When I try to access edges array, I get "TypeError: Cannot read property 'edges' of undefined".
JS code:
import data from "./__mocks__/blog.json";
console.log(data);
data.allMarkdownRemark.edges.forEach((post) => {
console.log(post);
})
Console.log(data):
{ data: { allMarkdownRemark: { edges: [Array] } }
My JSON file is formatted as a JSON object, so it is not necessary to use JSON.parse()
JSON file:
{
"data": {
"allMarkdownRemark": {
"edges": [
{
"node": {
"id": "c60d0972-1f4a-55ae-b762-c24795fae501",
"fields": {
"slug": "/a-tu-cerebro-no-le-gusta-la-innovacion/"
},
"frontmatter": {
"title": "A tu cerebro no le gusta la Innovación",
"templateKey": "blog-post",
"date": "September 16, 2017"
}
}
},
{
"node": {
"id": "1624f260-4c77-55d3-8297-4f0ad688f878",
"fields": {
"slug": "/la-mente-es-para-tener-ideas-no-para-almacenarlas/"
},
"frontmatter": {
"title": "La mente es para tener Ideas™, no para almacenarlas",
"templateKey": "blog-post",
"date": "August 26, 2017"
}
}
}
]
}
}
}
Do you know how to import correctly "edges" array of objects from JSON file?
The problem is your variable is called data and inside your json file you also defined data as a key. So you have to use data once as the variable and a second time as the key of the JSON file.
you have to access it like this:
data.data.allMarkdownRemark.edges.forEach((post) => {
console.log(post);
})
Another solution would be to change the structure of your JSON file.
You can:
import { data } from "./__mocks__/blog.json";
I'm using Node.js to:
Query an external API.
Save JSON result to file.
Import query result to MongoDB.
Example of code:
//Query the API and save file
var file = '../data/employees.json';
tl.employees.all(function(response) {
fs.writeFile(file, JSON.stringify(response, function(key, value) {
var result = value;
return result;
}, 3, 'utf8'));
//Inserts API response above to MongoDB
var insertDocument = function(db, callback) {
db.collection('employees').insert(response, function(err, result) {
assert.equal(err, null);
console.log("Step 2: Inserted Employees");
callback();
});
};
This is all working fine, and I'm getting the following JSON saving to file and importing to MongoDB:
{
"data": [
{
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
}
The problem is that this gets imported to MongoDB as 1 object because of the "data" part.
Like this:
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"data" : [
{ // contents as shown in JSON above ..
This makes aggregation and matching really hard (or not possible).
Is there a way of stripping out the "data" part and only importing the contents of it, so each 'employee' would become it's own object like this:
[
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"_id" : ObjectId("234332c10d7a5005fc8370"),
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
So you can parse the Json before sending it to file. After getting the result, use parseJSON(data) to check if it contains "data" field. if yes, get the arrays inside that and store them to file.
Basically, I have explained a bit more to what #Bertrand has said.
Hope this helps.