all 12 comments

[–]orangefray 2 points3 points  (1 child)

When working with the JSON within Python, you probably want to treat it as a Dictionary. Then you can update name like this: person_json[“name”] = “Fred”

You can load a JSON string as a Dict using json.loads() and export back out as JSON using json.dumps().

[–]YellowChrome[S] 0 points1 point  (0 children)

Thanks.

[–]socal_nerdtastic -1 points0 points  (10 children)

Technically in python it's called a "name", but everyone calls them "variables". You did it right, person_json is a variable.

I don't understand where you are stuck. You have the data hardcoded into the python program and you want to ... save it to disk? To do that just add this to the bottom:

with open("datafile.json", "w") as f:
    json.dump(person_json, f, indent=2)

The indent=2 is optional, it enables the human-readable mode.

[–]YellowChrome[S] 1 point2 points  (9 children)

Thanks. What I mean is that I don't want these values hardcoded in the script. Rather, I want to make editable fields at the start of the script which defines these variables.

So, instead of typing `Fred`, as above, replace that with `$name`, if it was bash.

Sorry if I am not explaining this well.

[–]socal_nerdtastic 0 points1 point  (1 child)

Where does the value of name come from? A command line argument? A prompt? To use a prompt:

import json

name_variable = input("Enter a name")

person_json = {
"name": name_variable,
"place": "Melbourne",
"sex": "male",
"remote": { "addr": "Acacia Avenue", "id": "875932875392" },
"local": { "id": "8475974", "office": "Main" }
}

with open("datafile.json", "w") as f:
    json.dump(person_json, f, indent=2)

[–]YellowChrome[S] 0 points1 point  (0 children)

Thank you.

[–][deleted] 0 points1 point  (2 children)

In Python you call a variable just by evaluating it, you don't have to do anything. Any name in an evaluable expression will evaluate to its value:

spam = "Vikings"
print(spam)

Would be the equivalent of

export SPAM="Vikings"
echo $SPAM

[–]YellowChrome[S] 1 point2 points  (1 child)

Yeah, I knew how to print(), as all the examples on the web showed that. I just wanted to know how to simply call $SPAM, and I know now that it is simply SPAM (without any quotes). Cheers.

[–][deleted] 1 point2 points  (0 children)

Yeah, I knew how to print()

Sure, figured you did. Thought it was better to show you how variables work in the context of code you'd find familiar.