Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Variables from a external .json file Python

What I need help with

I want to receive variables from a external .json file in the local directory using python27

(import doesn't work)

I want to store the variables in the .json like below

value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"

and have them being used in a script.

If I can get it to the point of which the .json includes

value1 = "this_is_value1"

and my .py includes

print(value1)

with output

>>>this_is_value1

I can take it from there

My end Task

The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.

I've done this part fine, just need to do this part

Have I researched the issue?

In short, YES.

however, theses answer use .py or other file types.

I've already tried importing the file but since it needs to sit next to the script I can't use import

Other anwser simply give no information back about how they solved the issue.

like image 890
Teobot Avatar asked Aug 30 '26 00:08

Teobot


1 Answers

With a json formatted file (say "my_file.json"), for instance:

{
  "x": "this is x",
  "y": "this is x",
  "z": "this is z"
}

Then in Python:

import json

with open("my_file.json", "r") as f:
    my_dict = json.load(f)
print(my_dict["x"])

Yields:

this is x
like image 89
Adonis Avatar answered Sep 01 '26 14:09

Adonis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!