Update Json value in python - python

I am trying to specify a name for my google spreadsheet api. This is done in the 'title' key value. I have tried with the below but it adds a new key to the existing json. Is there a way to get to the "title": "" and update that value with the new_date item?
prev_date = datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
res = {
"requests": [
{
"addSheet": {
"properties": {
"title": ""
}
}
}
]
}
res['title'] = new_date
print (res)
This is the output:
{'requests': [{'addSheet': {'properties': {'title': ''}}}], 'title': '2016-12-29'}
This is what I would like it to be:
{'requests': [{'addSheet': {'properties': {'title': '2016-12-29'}}}]}

From the structure you mentioned, the title key that you need to modify is more nested than what you are providing with.
You need to make the following change:
prev_date = datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
res = {
"requests": [
{
"addSheet": {
"properties": {
"title": ""
}
}
}
]
}
res['requests'][0]['addSheet']['properties']['title'] = new_date
print (res)
Where:
'requests' value is a list
0 is the first item in the list (and the only item)
'addSheet' is the key in the dictionary that is the value of the item in the list in the 0 index
'properties' is the key in the above dictionary
'title' is the key in the above dictonary, and the one you need upon your request

You are incorrectly indexing your JSON object and adding a new key named 'title' in the root of the object, while you are trying to update the value inside the array. In your case, you should be accessing res['requests'][0]['addSheet']['properties']['title'] = new_date

I now realize I can pass my variables directly in the json.
prev_date = datetime.date.today()-datetime.timedelta(1)
new_date = str(prev_date.isoformat())
req = {
"requests": [
{
"addSheet": {
"properties": {
"title": new_date
}
}

Related

copying data from json response [Python]

I have a scenario where I am trying to extract data from json response which is obtained from the GET request and then rebuilding the json data by changing some values and then sending a PUT request at same time after rebuilding the json data(i.e, after changing idter value)
below is the target json response.
target_json = {
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
from the above json I am trying to change the idter value to my custom value and rebuild it into json data again and post the new json data.
Here is what I have tried :
headers = {'Authorization': 'bearer ' + auth_token, 'Content-Type':'application/json', 'Accept':'application/json'}
tesstid =[7865, 7536, 7789]
requiredbdy = []
for key in testid:
get_metadata_targetjson= requests.get('https://myapp.com/%s' %key, headers = headers)
metadata=get_metadata_target.json()
for key1 in metadata:
requiredbdy.append(
{
"metadata" : [{
"name": key1['name'],
"ts": key1['ts'],
"gs": key1[gs],
"idter": 100, #custom value which I want to change
"datapart": false
} ]
}
)
send_metadata_newjson= requests.put('https://myapp.com/%s' %key, headers = headers data = requiredbdy)
print(send_metadata_newjson.status_code)
Is this approach fine or How do I proceed in order to achieve this scenario.
You can use the built-in json module for this like so
import json
my_json = """
{
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
"""
json_obj = json.loads(my_json)
json_obj['idter'] = 600
print(json.dumps(json_obj))
Prints
{"name": "toggapp", "ts": [1234, 3456], "gs": [{"id": 4491, "con": "mno"}, {"id": 4494, "con": "hkl"}], "idter": 600, "datapart": false}
There's this small script used it to find entries in some very long and unnerving JSONs. not very beautifull und badly documented but maybe helps in your scenario.
from RecursiveSearch import Retriever
def alter_data(json_data, key, original, newval):
'''
Alter *all* values of said keys
'''
retr = Retriever(json_data)
for item_no, item in enumerate(retr.__track__(key)): # i.e. all 'value'
# Pick parent objects with a last element False in the __track__() result,
# indicating that `key` is either a dict key or a set element
if not item[-1]:
parent = retr.get_parent(key, item_no)
try:
if parent[key] == original:
parent[key] = newval
except TypeError:
# It's a set, this is not the key you're looking for
pass
if __name__ == '__main__':
alter_data(notification, key='value',
original = '********** THIS SHOULD BE UPDATED **********',
newval = '*UPDATED*')

Join array of objects to string value in Python

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)

Iterating a python object and filtering it

The JSON notation I get from the Webservice:
{
"students": [
{
"studentId": 127292,
"studentName": "Mary"
},
{
"studentId": 15555,
"studentName": "Joe"
}
]
}
I am trying to iterate the JSON object and get student id based on the student name.
For example, if I have to get studentId of 'Joe', how we can process that in Python?
try:
req = urllib2.Request(url, headers = header)
response = urllib2.urlopen(req)
jsonObject = json.load(response)
except Exception as e:
print e
i suggest to remap your data to a dictionary where you can lookup your students by name:
data = {
"students": [
{
"studentId": 127292,
"studentName": "Mary"
},
{
"studentId": 15555,
"studentName": "Joe"
}
]
}
lookup = {student["studentName"]: student["studentId"] for student in data["students"]}
id_of_joe = lookup.get("Joe", "No student named Joe")
You can iterate over the JSON object to get the student ID in each field
studentIds = []
for obj in jsonObject:
sID = obj['studentId']
studentIds.append(sID)

How to manipulate an object of Google Ads API's Enum class - python

I am using the python client library to connect to Google Ads's API.
ga_service = client_service.get_service('GoogleAdsService')
query = ('SELECT campaign.id, campaign.name, campaign.advertising_channel_type '
'FROM campaign WHERE date BETWEEN \''+fecha+'\' AND \''+fecha+'\'')
response = ga_service.search(<client_id>, query=query,page_size=1000)
result = {}
result['campanas'] = []
try:
for row in response:
print row
info = {}
info['id'] = row.campaign.id.value
info['name'] = row.campaign.name.value
info['type'] = row.campaign.advertising_channel_type
When I parse the values this is the result I get:
{
"campanas": [
{
"id": <campaign_id>,
"name": "Lanzamiento SIKU",
"type": 2
},
{
"id": <campaign_id>,
"name": "lvl1 - website traffic",
"type": 2
},
{
"id": <campaign_id>,
"name": "Lvl 2 - display",
"type": 3
}
]
}
Why am I getting an integer for result["type"] ? When I check the traceback call I can see a string:
campaign {
resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
id {
value: 397083380
}
name {
value: "Lanzamiento SIKU"
}
advertising_channel_type: SEARCH
}
campaign {
resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
id {
value: 1590766475
}
name {
value: "lvl1 - website traffic"
}
advertising_channel_type: SEARCH
}
campaign {
resource_name: "customers/<customer_id>/campaigns/<campaign_id>"
id {
value: 1590784940
}
name {
value: "Lvl 2 - display"
}
advertising_channel_type: DISPLAY
}
I've searched on the Documentation for the API and found out that it's because the field: advertising_channel_type is of Data Type: Enum. How can I manipulate this object of the Enum class to get the string value? There is no helpful information about this on their Documentation.
Please help !!
The Enum's come with some methods to translate between index and string
channel_types = client_service.get_type('AdvertisingChannelTypeEnum')
channel_types.AdvertisingChannelType.Value('SEARCH')
# => 2
channel_types.AdvertisingChannelType.Name(2)
# => 'SEARCH'
This was found by looking at docstrings, e.g.
channel_types.AdvertisingChannelType.__doc__
# => 'A utility for finding the names of enum values.'
I think the best way to do this is this one liner code:
import proto
row_dict = proto.Message.to_dict(google_ads_row, use_integers_for_enums=False)
This will convert the entire google ads row into a dictionary in just one go and automatically get the ENUM values instead of the numbers.
#Vijaysinh Parmar try following
from google.protobuf import json_format
row_dict = json_format.MessageToJson(row, use_integers_for_enums=False)
Just work around it by, create a list
lookup_list = ['DISPLAY', 'HOTEL', 'SEARCH', 'SHOPPING', 'UNKNOWN', 'UNSPECIFIED', 'VIDEO']
and change the assignment in your last row to
info['type'] = lookup_list[row.campaign.advertising_channel_type]

Replace value in JSON file for key which can be nested by n levels

I have JSON that looks like this:
{
"ROLE_NAME": {
"FOO": {
"download_url": "http: //something.staging/12345/buzz.zip"
},
"BAR": {
"download_url": "http: //something.staging/12345/fizz.zip"
},
"download_url": "http: //something.staging/12345/fizzbuzz.zip",
"db_name": "somedb",
"db_server": "dbserver.staging.dmz",
"plugin": {
"server_url": "http: //lab.staging.corp/server/"
}
}
}
I wrote a bit of python that replaces the "download_url" k:v with a new value (i.e. new download_url). Unfortunately it only replaces one of the three download_urls in that json snippet. I understand why, but am having a little difficulty getting the solution, and so I am here asking for help.
The entire json object is "data"
So I do something like this:
data["ROLE_NAME"]["download_url"] = download_url
Where download_url is a new value I have assigned to that variable
What I need to do is for any key called ["download_url"] then update it, rather than the one I have specified at the layer I am going to.
Some of my code to help:
I take some values obtained earlier in my code and build a url which returns a response. I extract a value from the response which will be used to build the value of download_url
buildinfo_url = "http://something.staging/guestAuth/app/rest/builds/?locator=buildType:%s,tags:%s,branch:branched:any" % (
bt_number,
list_json_load[role_name][0]['tag']
)
Send HTTP request
client = httplib2.Http()
response, xml = client.request(buildinfo_url)
Extract some value from the response xml and set download_url variable
doc = ElementTree.fromstring(xml)
for id in doc.findall('build'):
build_id = "%s" % (id.attrib['id'])
try:
download_url = "http://something.staging/guestAuth/repository/download/%s/%s:id/%s" % (
bt_number,
build_id,
build_artifact_zip
)
data[role_name]["download_url"] = download_url
except NameError:
print "something"
I think I should be recursively searching and updating
Using recursion
import json
json_txt = """
{
"ROLE_NAME": {
"FOO": {
"download_url": "http: //something.staging/12345/buzz.zip"
},
"BAR": {
"download_url": "http: //something.staging/12345/fizz.zip"
},
"download_url": "http: //something.staging/12345/fizzbuzz.zip",
"db_name": "somedb",
"db_server": "dbserver.staging.dmz",
"plugin": {
"server_url": "http: //lab.staging.corp/server/"
}
}
}
"""
data = json.loads(json_txt)
def fixup(adict, k, v):
for key in adict.keys():
if key == k:
adict[key] = v
elif type(adict[key]) is dict:
fixup(adict[key], k, v)
import pprint
pprint.pprint( data )
fixup(data, 'download_url', 'XXX')
pprint.pprint( data )
Output:
{u'ROLE_NAME': {u'BAR': {u'download_url': u'http: //something.staging/12345/fizz.zip'},
u'FOO': {u'download_url': u'http: //something.staging/12345/buzz.zip'},
u'db_name': u'somedb',
u'db_server': u'dbserver.staging.dmz',
u'download_url': u'http: //something.staging/12345/fizzbuzz.zip',
u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
{u'ROLE_NAME': {u'BAR': {u'download_url': 'XXX'},
u'FOO': {u'download_url': 'XXX'},
u'db_name': u'somedb',
u'db_server': u'dbserver.staging.dmz',
u'download_url': 'XXX',
u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}

Categories

Resources