I am new to the JSON python lib.
I have this JSON file:
{
"usrdata": [
{
"user": "---/ LandiPlayz \\---#****",
"money": 10
},
{
"user": "Snubz#****",
"money": 10
}
]
}
and I need to modify the "money" field of one of the users. There will be more added users, so I need to find which one it is by finding the users name. Is that possible, or should I do format the file differently.
Thanks in advance
You have to iterate over the user_infos, and when getting the good one, update the money
json_value = {
"usrdata": [
{"user": "---/ LandiPlayz \\---#****","money": 10},
{"user": "Snubz#****","money": 10}
]
}
username = "Snubz#****"
new_money = 50
for user_info in json_value["usrdata"]:
if user_info['user'] == username:
user_info['money'] = new_money
Related
I'm trying to add a new json field conditionally looking for others fields values using python, like that:
{
"id":"x2342345ap",
"quantity":1,
"timestamp":"2022-09-26",
"details":[
{
"name":"robert",
"color":"red",
"age": 25
}
]
}
And then looking into the details.field (name, color, age) create a new field. Like, if the name is different of James, add 'ugly name' to an array for this new field and the same for the color:
{
"id":"x2342345ap",
"quantity":1,
"timestamp":"2022-09-26",
"problems": ['ugly name', 'ugly color']
"details":[
{
"name":"robert",
"color":"red",
"age": 25
}
]
}
You can treat JSON similarly to how you interact with native dictionaries and lists. For example, I'll start with a string, convert to JSON, and then add a note to the list of problems:
import json
jsonstring = """
{
"id":"x2342345ap",
"quantity":1,
"timestamp":"2022-09-26",
"details":[
{
"name":"robert",
"color":"red",
"age": 25
}
]
}
"""
myjson = json.loads(jsonstring)
if myjson["details"][0]["name"] == "robert":
if "problems" not in myjson:
myjson["problems"] = ["good name!"]
else:
myjson["problems"].append("good name!")
I have below class defined to do statistics for voting system.
class FormPage(AbstractForm):
submission_stats = models.JSONField(null=True, editable=False)
Now, I have submission_stats in below format:
[
{
"id":4,
"label":"checkboxes",
"choices":[
{
"content":"option-A",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-B",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-C",
"num_vote":0,
"user_list":[
]
}
]
},
{
"id":7,
"label":"Radio Button",
"choices":[
{
"content":"option-1",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-2",
"num_vote":0,
"user_list":[
]
},
{
"content":"option-3",
"num_vote":0,
"user_list":[
]
}
]
}
]
When I receive 2 vote submissions for example, I want to update num_vote (from 0 to 2) and user_list (from [] to [user_a, user_b]) field in this JSONField accordingly.
How to query and update elements in nested JSONField data please ?
install json library
pip install json
import json
data = json.load(submission_stats)
now this data is python dictionary. update it however you want
to save updated data back to json field, convert dictionary back to json like this
json.dumps(data, indent = 4)
and save
plus if you want to use sql with your this project i highly recomment you use
from django_extensions.db.fields.json import JSONField
instead of
models.JSONField
because models.JSONField doesn't go well with SQL
I want to write a program that will save information from the API, in the form of a JSON file. The API has the 'exchangeId' parameter. When I save information from the API, I want to save only those files in which the 'exchangeId' will be different and his value will be more then one. How can I make it? Please, give me hand.
My Code:
exchangeIds = {102,311,200,302,521,433,482,406,42,400}
for pair in json_data["marketPairs"]:
if (id := pair.get("exchangeId")):
if id in exchangeIds:
json_data["marketPairs"].append(pair)
exchangeIds.remove(id)
pairs.append({
"exchange_name": pair["exchangeName"],
"market_url": pair["marketUrl"],
"price": pair["price"],
"last_update" : pair["lastUpdated"],
"exchange_id": pair["exchangeId"]
})
out_object["name_of_coin"] = json_data["name"]
out_object["marketPairs"] = pairs
out_object["pairs"] = json_data["numMarketPairs"]
name = json_data["name"]
Example of ExchangeIds output, that I don't need:
{200} #with the one id in `ExchangeId`
Example of JSON output:
{
"name_of_coin": "Pax Dollar",
"marketPairs": [
{
"exchange_name": "Bitrue",
"market_url": "https://www.bitrue.com/trade/usdp_usdt",
"price": 1.0000617355334473,
"last_update": "2021-12-24T16:39:09.000Z",
"exchange_id": 433
},
{
"exchange_name": "Hotbit",
"market_url": "https://www.hotbit.io/exchange?symbol=USDP_USDT",
"price": 0.964348817699553,
"last_update": "2021-12-24T16:39:08.000Z",
"exchange_id": 400
}
],
"pairs": 22
} #this one of exapmle that I need, because there are two id
I want to join array of objects to a string in python. Is there any way for me to do that?
url = "https://google.com",
search = "thai food",
results = [
{
"restaurant": "Siam Palace",
"rating": "4.5"
},
{
"restaurant": "Bangkok Palace",
"rating": "3.5"
}
]
I want to be able to join these all to form one value.
If I could make it look like:
data = { url = "https://google.com",
{
search = "thai food",
results = [
{
"restaurant": "Siam Palace",
"rating": "4.5"
},
{
"restaurant": "Bangkok Palace",
"rating": "3.5"
}
]
}
}
I am receiving these results from mongodb and want to join these 3 together.
Use the JSON module
data = {} # create empty dict
# set the fields
data['url'] = 'https://google.com'
data['search'] = 'thai food'
# set the results
data['results'] = results
# export as string
import json
print(json.dumps(data, indent=4)
Is there any way to pull the key from JSON if the only thing I know is the value? (In groovy or python)
An example:
I know the "_number" value and I need a key.
So let's say, known _number is 2 and as an output, I should get dsf34f43f34f34f
{
"id": "8e37ecadf4908f79d58080e6ddbc",
"project": "some_project",
"branch": "master",
"current_revision": "3rtgfgdfg2fdsf",
"revisions": {
"43g5g534534rf34f43f": {
"_number": 3,
"created": "2019-04-16 09:03:07.459000000",
"uploader": {
"_account_id": 4
},
"description": "Rebase"
},
"dsf34f43f34f34f": {
"_number": 2,
"created": "2019-04-02 10:54:14.682000000",
"uploader": {
"_account_id": 2
},
"description": "Rebase"
}
}
}
With Groovy:
def json = new groovy.json.JsonSlurper().parse("x.json" as File)
println(json.revisions.findResult{ it.value._number==2 ? it.key : null })
// => dsf34f43f34f34f
Python 3: (assuming that data is saved in data.json):
import json
with open('data.json') as f:
json_data = json.load(f)
for rev, revdata in json_data['revisions'].items():
if revdata['_number'] == 2:
print(rev)
Prints all revs where _number equals 2.
using dict-comprehension:
print({k for k,v in d['revisions'].items() if v.get('_number') == 2})
OUTPUT:
{'dsf34f43f34f34f'}