1

Consider this code, which is understandably failing:

def testDataTransform():
    source = 'data/threads/testFile2.json' 
    newFile = 'data/threads/testFile1.json'

    jX = returnJson(source)
    jY = returnJson(newFile)

    for dataL1 in jX:
        #print dataL1['city']
        for dataL2 in jY:
            if dataL1['city'] == dataL2['city']:
                dataL2.append(dataL1['population']) 

    print dataL2


# end testDataTransform

def returnJson(source):
    #Grab destination file json
    try:
       with open(source) as jsonFile: # Open and verify file is there
        # load JSON object into memory
        j = json.load(jsonFile)

        return j
    except Exception, e:
        print e
        raise
# end returnJson

testDataTransform()

The error generated is: AttributeError: 'dict' object has no attribute 'append', which I now understand is due to trying to use append on a file steam and thus appending my JSON incorrectly. The question is how would I do this correctly? I want to add population data, which is in the source file.

JSON structure in testFiles look like this:

[

    {
        "city": "New York",
        "lat": 20.1234,
        "long": 32.09876
    },
    {
        "city": "London",
        "lat": 21.1234,
        "long": 37.09876
    },
    {
        "city": "New Jersey",
        "lat": 10.1234,
        "long": 30.09876
    }

]

One has a "population" node and other does not. I want to copy that population data from one file to another. How is that done? I wonder if converting the file stream into an array would help, but how do I even do that?

Thanks.

0

1 Answer 1

1

The error message is telling you exactly what's wrong. It's in this line

dataL2.append(dataL1['population']) 

dataL2 is a dict(), and dict() does not have a method called append

What you want is

dataL2["population"] = dataL1['population']

Basically, the call to json.load() for this file returns a list of dicts(). JSON arrays map to Python lists, JSON objects map to Python dictionaries. To add a new key to a dict, simply set a value on it.

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

3 Comments

Well look at that! Nice. But now the values are all the same for every object
Didn't say that was your only problem :) What's the contents of the other test file?
check the indentation in your modified code. Is the assignment only happening when the if condition is met?

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.