Python json How to add data - python

I don't speak English well
So the question may be a bit odd
{
"arg1": {
"1": "1",
"2": "2"
},
"arg2": {
"1": "1",
"2": "2"
},
"arg3": {
"1": "1",
"2": "2"
}
}
I want to store data this way. What should I do?
json_data = {arg3: {"1": "1", "2": "2"}}
with open(f'./Json/test.json', 'w', encoding='utf-8') as make_file:
json.dump(json_data, make_file, ensure_ascii=False ,indent="\t")
Is this right?
I would appreciate it if you let me know.
I don't know what to do by deleting the original content.

Your code works fine. The only problem I see when your running it is that that arg3 needs to be written as "arg3" in double quotes (single quotes are invalid in json) unless you have a value for it defined previously.
json_data = {"arg3": {"1": "1", "2": "2"}}
Make that change, and you should be able to load and properly display your JSON with:
with open(f'output.json') as f:
a = json.load(f)
print(json.dumps(a, indent="\t"))
If you do the json.dumps() you get a properly formatted json which you can then call print on to display.

Related

Reading a JSON file in python, reading a value and assigning it to a variable [duplicate]

This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed last month.
I have a json file which looks like
{
"0": {
"id": 1700388,
"title": "Disconnect: The Wedding Planner",
"year": 2023,
"imdb_id": "tt24640474",
"tmdb_id": 1063242,
"tmdb_type": "movie",
"type": "movie"
},
"1": {
"id": 1631017,
"title": "The Pale Blue Eye",
"year": 2022,
"imdb_id": "tt14138650",
"tmdb_id": 800815,
"tmdb_type": "movie",
"type": "movie"
},
"2": {
"id": 1597915,
"title": "The Man from Toronto",
"year": 2022,
"imdb_id": "tt11671006",
"tmdb_id": 667739,
"tmdb_type": "movie",
"type": "movie"
},
I am trying to read this and extract the "tmbd_id" to store as a variable. I then intend to inject this into a url for an api get request.
The next step is to add the response parameters to the json file. Then adding it all into a loop. There are 1000 entries.
I have been trying to use other answers but I suspect the nature of my json is causing the issue with the integer name causing issues. It has been giving me this error
for i in data['0']:
TypeError: list indices must be integers or slices, not str
You can use json.loads to read the file's content and then iterate to find those id's:
import json
tmdb_ids = []
with open('test.json', 'r') as json_fp:
imdb_info = json.load(json_fp)[0]
for dict_index, inner_dict in imdb_info.items():
tmdb_ids.append(inner_dict['tmdb_id'])
print(tmdb_ids)
Result:
[1063242, 800815, 667739]
You can make it more sophisticated if you need a specific tmdb_id from a specific "movie" by adding some if statements to the for loop, choosing movies you want.
Edit
I've noticed this is an array of dictionaries, thus we can iterate over each "movie chunk" and extract the tmdb_id from each one:
with open('test.json', 'r') as json_fp:
imdb_info = json.load(json_fp)
tmdb_ids = [movie_info['tmdb_id'] for movies_chunk in imdb_info for movie_index, movie_info in movies_chunk.items()]
for reading json:
import json
with open("file.json","r") as file:
text = json.load(file)
for tmbd_id:
for i in text:
print(text[i]["tmdb_id"])

When I try to read a JSON data from a file (exported from xlsx) in python, it throws KeyError

I had .xlsx file, and I converted it to JSON. I am using python to get the data from this json file. I am able for example to search for Build# and then I get the corresponding level, but when I search for values in, for example, "14H0232" or "14H4812" it throws a KeyError.
'''
import json
f = open('try.json')
data = json.load(f)
input= input('Enter the value: ')
for i in data['F6']:
if i['14H0232'] == input:
print(i['LEVEL'])
f.close()
'''
A Snippet of the json file.
'''
{
"F6": [
{
"LEVEL": "2.0.6.0",
"ID": "dataID",
"Build#": "9",
"prod/dev": "prod ",
"14H4812": "data1\r\ndata2",
"14H4826": "data",
"14H4813": "data1\r\ndata2"
}
],
"F5": [
{
"LEVEL": "2.0.5.1",
"ID": "dataID",
"Build#": "18",
"prod/dev": "prod",
"14H0232": "data1: data1\r\ndata2: data2\r\ndata3: data3",
"14H12321": "data1\r\ndata2"
}
],
"F4": [
{
"LEVEL": "2.0.4.1",
"ID": "dataID",
"Build#": "18",
"prod/dev": "prod",
"14H0232": "data1: data1\r\ndata2: data2\r\ndata3: data3",
"14H12321": "data1\r\ndata2"
}
]
}
'''
The problem is in your loop. When you are trying to access the value for "14H0232" it just doesnt exist in your json file. The case for 'Build#' is different I assume, as the key is always there. The example you shared is also not showing that F6 has a key with that id you specified.
So to avoid this kind of errors you can put your 'if' statement in a try block and catch the error.
try:
if i['14H0232'] == input:
print(i['LEVEL'])
except KeyError:
print("The key is not found but the code continues to execute")

Python Executing Json with backslash

I have json string, which i need to execute in selenium script using python, but i think /" making it difficult to parse
var t = {
"s": {
"2MqcJqtmNYDZlcbDZY3yjA==": "[{\"id\":\"global_mute\",\"expiration\":0}]",
"BrowserId": "\"TAMGVxD/wr9fL47xJZAciw==\"",
"SecretBundle": "{\"key\":\"2Eiw3rJZI9oErblie5mx+xXPjd+tj6t0hqQHC+EQ8Bc=\",\"encKey\":\"aGLPEm0dyq6W/gHN5cVONhdOR6lv2CGm4v4GLJ7LyoM=\",\"macKey\":\"2Eiw3rJZI9oErblie5mx+xXPjd+tj6t0hqQHC+EQ8Bc=\"}",
"Token1": "\"OG7aZ02ndonc1DGnfJ3bswG3na3Wr5OB7bwdgiwdd4Y=\"",
"Token2": "\"1#Sf53vRMCbVuLW0Q1diEg95TVBWRMDOjG7mqI8XIfOjr+hMiTwyqjKM72NKgxZJBGtfkETDmqfCgVLQ==\"",
"Xz+yNzfxx8EbdaUFWVxmjg==": "false",
"debugCursor": "191",
"ghI8QhVRLDvFWJDpV7Cx5g==": "false",
"logout-token": "\"1#MZ9F8QbLN9iGKNeZGbCJdzKwPHq7L5sJrpO6RtiG35rdu5TVLu/+z3gGNmbYG59h1Grzfwcnz44uLVencqRdP044ZpWuT02+ltcEM+9aCURZQkBG+oRyeWNAHcInXMWCpWysPF5d/ISLnbfeV1NVoA==\"",
"remember-me": "true",
"storage_test": "storage_test"
},
"c": ""
}
i used r'var t = whole json string', but its not working.
Do i need to covert backslash first ?

indent is broken after saving back updated json dict to file

I have a nested dictionary with many items in a json file:
{
"Create Code For Animals": {
"mammals": {
"dog": {
"color": "brown",
"name": "John",
"legs": "four",
"tail": "yes"
},
"cat": {
"color": "blue",
"name": "Johnny",
"legs": "four",
"tail": "yes"
},
"donkey": {
"color": "grey",
"name": "Mickey",
"legs": "four",
"tail": "yes"
}
I want to replace the name in each one of the animals, then save it back to the file, AND keep the indent as it was (as shown).
I'm using the following 2 methods for loading and dumping the original and updated dictionary.
All is working well (for changing the value and saving it back to the file) except the indent (format) of the lines is ruined after saving the file and the file is saved as one long line (with '\n' shown after the updated value).
I've tried using 'pickle' (as seen in one of the posts here), but this didn't work, made a mess of all the data in the file.
def loadJson(self, jsonFilename):
with open(FILE_PATH + '\\' + jsonFilename, 'r') as f:
return json.load(f)
def writeJson(self, jsonFilename, jsonDict):
with open(FILE_PATH + '\\' + jsonFilename, 'w') as f:
return json.dump(jsonDict, f)
Any help will do.
json.dumps and dump have a parameter called indent
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the default item separator is ``', '``, the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ': ')`` to avoid this
Something like this would do:
json.dump(jsonDict,f,indent=4)

python loop with JSON, rather then manually print out each match

I have successfully written a script to pull information from a json file and parse this in a way in which I will I can use but I at the moment I have to manually print each string. I would like to loop this if possible but stuck on where to start?
Python
from __future__ import print_function
import json
import sys
from pprint import pprint
with open('screen.json') as data_file:
data = json.load(data_file)
#json_file.close()
# Print all json data
#pprint(data)
#screen_list = data['screen']
print ("Screens availble",len (data['screen']))
#pprint(data["screen"][1]["id"])
#pprint(data["screen"][1]["user"])
#pprint(data["screen"][1]["password"])
#pprint(data["screen"][1]["code"])
#How to loop this
print ("https://",data["screen"][0]["server"],"/test/test.php?=",data["screen"][0]["code"],sep='')
print ("https://",data["screen"][1]["server"],"/test/test.php?=",data["screen"][1]["code"],sep='')
print ("https://",data["screen"][2]["server"],"/test/test.php?=",data["screen"][2]["code"],sep='')
JSON
{
"screen": [
{
"id": "1",
"user": "user1#example.com",
"password": "letmein",
"code": "123456",
"server": "example.com"
},
{
"id": "2",
"user": "user2#example.com",
"password": "letmein",
"code": "123455",
"server": "example.com"
},
{
"id": "3",
"user": "user3#example.com",
"password": "letmein",
"code": "223456",
"server": "example.com"
}
]
}
You've already pulled data['screen'] out into a variable named screen_list. That variable is a list, so you can use it the same as any other list—call len on it, index it, or loop over it. So:
screen_list = data['screen']
print("Screens availble", len(screen_list))
for screen in screen_list:
pprint(screen['id'])
pprint(screen['user'])
pprint(screen['password'])
pprint(screen['code'])
And, down below, just loop again:
for screen in screen_list:
print("https://", screen["server"], "/test/test.php?=", screen["code"], sep='')
(I'm assuming you want to print out all the screens' info, then print out all the URLs. If you want to print each URL at the same time you print the info, just merge them into one loop.)
As a side note, this is a good time to learn about string formatting. If you want to use those URLs to, e.g., pass them to urllib2 or requests, you can't just print them out, you have to make them into strings. Even if you do just want to print them out, formatting is usually easier to read and harder to get wrong. So:
print("https://{}/test/test.php?={}".format(screen["server"], screen["code"]))
… or …
print("https://{server}/test/test.php?={code}".format(**screen))
You can iterate over the list of dicts:
for d in data["screen"]:
print ("https://",d["server"],"/test/test.php?=",d["code"],sep='')
Out:
https://example.com/test/test.php?=123456
https://example.com/test/test.php?=123455
https://example.com/test/test.php?=223456

Categories