0

How does one do string formatting on nested dictionaries with triple quotes?

I have an api that I am hitting which requires my data field to be formatted in a particular way.

    values = """{
        "profile": {
          "census_tract": "41051003901",
          "street_address": "123 N Fake Ave",
          "city": "Portland",
          "state": "OR",
          "zip_code": "97203",
          "lat": 45.0000,
          "lon": -122.00000
        }
      }"""

I would like to do something along the lines of

      {
        "profile": {
          "census_tract": "{0}",
          "street_address": "{1}",
          "city": "{2}",
          "state": "{3}",
          "zip_code": "{4}",
          "lat": {5},
          "lon": {6}
        }
      }
    """

    print(values.format(in_census_tract, in_street_address, in_city, in_state, in_zip, in_lat, in_long))

Instead of the correctly formatted string, I get the following:

'\n "profile"'

The only thing that works is really ugly...

    a = """
      {
        "profile": {"""
    b = ''' "census_tract": "{0}",
          "street_address": "{1}",
          "city": "{2}",
          "state": "{3}",
          "zip_code": "{4}",
          "lat": {5},
          "lon": {6}
          '''
    c = """
        }
      }
    """
    values = a + b.format(in_census_tract, in_street_address, in_city, in_state, in_zip, in_lat, in_long) + c
CENTURION
  • 355
  • 3
  • 11
  • 1
    Don't build JSON manually. Build a Python data structure and then use [the `json` module](https://docs.python.org/3/library/json.html#module-json) to convert it to JSON. This has many benefits, but one is that putting dynamic values into your data will become trivial. – ChrisGPT was on strike Sep 04 '19 at 02:55
  • Possible duplicate of [How to dynamically build a JSON object with Python?](https://stackoverflow.com/questions/23110383/how-to-dynamically-build-a-json-object-with-python) – ChrisGPT was on strike Sep 04 '19 at 02:57

1 Answers1

0

Ah, I see

so I would do the following

tract = "41051003901"
street_address = "123 N Fake Ave"
city = "Portland"
state = "OR"
zipcode = "97203"
lat = 45.555551
long = -122.111111


values = {
    "profile": {
      "census_tract": tract,
      "street_address": street_address,
      "city": city,
      "state": state,
      "zip_code": zipcode,
      "lat": lat,
      "lon": long
    }
  }

dumper = json.dumps(values, indent=4)

print(dumper)
CENTURION
  • 355
  • 3
  • 11