0

I am doing multiple requests to a REST service and getting JSON data back from each request. What I want to do is merge all of those JSON objects (hoping I am using the right terminology) into one object. How do I do that?

minCount = 1
maxCount = 1000
masterJson = {}
for x in range(36):
    params = {'f': 'json', 'where': 'OBJECTID>='+str(minCount)+'and OBJECTID<='+str(maxCount), 'geometryType': 'esriGeometryPolygon', 'spatialRel': 'esriSpatialRelIntersects','outFields': '*', 'returnGeometry': 'true'}
    r = requests.get('https://hazards.fema.gov/gis/nfhl/rest/services/CSLF/Prelim_CSLF/MapServer/3/query', params)

    cslfJson = r.json()
    masterJson.update(cslfJson)

    for item in cslfJson['features']:
        objCount = item['attributes']['OBJECTID']

        if minCount < objCount:
            break
        else:
        minCount = minCount + maxCount
        maxCount = maxCount + 1000

Essentially, its the cslfJson variables (JSON obj) that I want to combine into one cslfJson object variable.

5
  • Every time you run masterJson.update(cslfJson) the data in masterJson will be replaced, is it intentional? Commented Aug 22, 2018 at 20:11
  • No. That is part of the issue. I want it to add each iteration of the cslfJson data, not update it with the new data. Commented Aug 22, 2018 at 20:27
  • 1
    why don't you use masterJson = [] and do masterJson.append(cslfJson) to collect all responses? Commented Aug 22, 2018 at 20:33
  • I actually considered that earlier. Would I then be able to convert that masterJson list into a dictionary/JSON object? Doesn't json.dump() do that? Commented Aug 22, 2018 at 20:35
  • You should be able to json.dump() anything that is a valid json. You can test json here jsoneditoronline.org. A list of objects is a valid json object. Commented Aug 22, 2018 at 20:42

1 Answer 1

1

In the memory JSON objects are treated like a dict so treat each JSON obj as a dict.

masterJson = {}
masterJson['JSON1'] = cslfJson
masterJson['JSON2'] = cslfJson

If you need to write a .json file, you can just pass the whole dict as argument to the JSON writers.

Sign up to request clarification or add additional context in comments.

3 Comments

This essentially works. However, adding the new name for each separate object complicates things a bit because of processing further down the line (these objects are used to create spatial features in GIS in a later stage).
you can use a variable as the key masterJson[variable] = cslfJson. just the keys should be unique.
I opened another question that may resolve my issue: stackoverflow.com/questions/51989564/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.