0

I am sending a JSON request to a server and need to access a time-stamp so it dynamically changes based on another time variable. I am using requests to send a post request with the JSON as a .txt file.

My JSON is here. I would like to be able to access the dateAndTime field so that I can use the current time to send my query. The json is consumed by the server as data2 =jsonpickle.encode(jsonpickle.decode(f2.read()) )

f2 is the json file.

Here is my post request that I would ultimately have this changed;

dateAndTime parameter in r2 = requests.post(url2, data=data2, headers=headers2,timeout=(connect_timeout, 10))

{
    "RequestSpecificDetail": {
        "ParentSRNumberForLink": ""
    },
    "MetaData": {
        "appVersion": "1.34",
        "deviceModel": "x86_64",
        "dateAndTime": "01/15/2015 12:46:36",
        "deviceToken": "A2C1DD9D-D17D-4031-BA3E-977C250BFD58",
        "osVersion": "8.1"
    },
    "SRData": {
        "SRNumber": "1-3580171"
    }
}
AlG
  • 14,697
  • 4
  • 41
  • 54
hgs
  • 87
  • 1
  • 2
  • 9
  • Possible duplicate of http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python – AlG Apr 14 '15 at 16:51

2 Answers2

0

The trick is to get the data as a dictionary. You can use literal_eval for this:

import ast
data_as_dict = ast.literal_eval(data2)

You can get the current time with:

import datetime
now = datetime.now().strftime('%m/%d/%Y %H:%M:%S')
data_as_dict['MetaData']['dateAndTime'] = now

Then you can pass data_as_dict instead of data2; probably using the 'json=data_as_dict' argument instead of 'data=' when calling requests.post()

Use this link for information about all the formatting options.

Joe
  • 2,496
  • 1
  • 22
  • 30
  • yeah except it looks like data2 is actually a string – Joran Beasley Apr 14 '15 at 16:55
  • Exactly, I have been receiving expecting an int error when going this route. How do I access the data in f2 before sending creating data2 and sending to server? – hgs Apr 14 '15 at 17:00
0
data2 = jsonpickle.decode(whatever)
data2["Metadata"]["dateAndTime"] = "Whatever"
data2 = jsonpickle.encode(data2)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179