0

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
2
  • you can access by DOT (.) OR SQUARE BRACKET ([ ]) Example:- const host = jsonFile.url OR const host = json["url"] Commented Dec 26, 2019 at 15:16
  • The principal problem here is that your JSON isn't JSON, because you forgot to put quotes around that IP address. Once you fix that, you can access the properties in jsonFile in the same way you'd access any property in a standard JS object (because that's what it now is: JSON is the string representation of a JS object; once parsed, it is an object, and no longer JSON string data) Commented Dec 26, 2019 at 15:29

4 Answers 4

2

Your json file should be:

{
  "server": "myname",
  "url": "10.0.0.1"
}

(use double quotes)

and just use dot:

const host = jsonFile.url
Sign up to request clarification or add additional context in comments.

Comments

1

In javascript, Specific Object value can be accessed by following three ways:

  1. DOT (.) operator

    const obj = {
       "server": "myname",
       "url": "10.0.0.1"
    };
    const url = obj.url;
    console.log(url); // 10.0.0.1
    
  2. Square bracket ([])

    const obj = {
       "server": "myname",
       "url": "10.0.0.1"
    };
    const url = obj["url"];
    console.log(url); // 10.0.0.1
    
  3. De-structuring (>=ES6)

    const obj = {
       "server": "myname",
       "url": "10.0.0.1"
    };
    const { url } = obj;
    console.log(url); // 10.0.0.1
    

Comments

0

You need to use the "dot" syntax.

const host = jsonFile.url

Comments

0

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.