Reputation: 1013
Im new to js and i dont understand how can i take an object from json file,
for example this file : local.json
{
"server": "myname",
"url": 10.0.0.1
}
I need to get the url to insert in in my js code like this, replace the 127.0.0.1 with what i have in json file at url:
import axios from 'axios';
import jsonFile from '../local.json';
const http = require("http");
const host = '127.0.0.1'; #should be 10.0.0.1 from json file
Upvotes: 0
Views: 120
Reputation: 65
I assume you need to get configurations to instantiate your server.
You may like to follow below steps to instantiate settings:
Install the dependency config
It allows you to define a json file of settings.
I define the structure
you create a directory inside your project called config
inside you create a json file default.json
│
config
│--- default.json
│
inside the file you write your values
{
"server": "myname",
"url": "10.0.0.1"
}
and to access you do the following
file = index.js
const config = require ("config");
console.log (config.get ("url"));
Upvotes: 0
Reputation: 312
In javascript, Specific Object value can be accessed by following three ways:
DOT (.
) operator
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const url = obj.url;
console.log(url); // 10.0.0.1
Square bracket ([]
)
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const url = obj["url"];
console.log(url); // 10.0.0.1
De-structuring (>=ES6)
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const { url } = obj;
console.log(url); // 10.0.0.1
Upvotes: 1
Reputation: 491
Your json file should be:
{
"server": "myname",
"url": "10.0.0.1"
}
(use double quotes)
and just use dot:
const host = jsonFile.url
Upvotes: 2