2

I need to pass a JSON object to a separate function in python

import json

userList = [{username: 'userName', email: 'email'}]

listString = json.dumps(userList)
print(json.loads(listString))

this will print the same object: [{username: 'userName', email: 'email'}]

I know it isn't possible to pass a JSON object directly to another function which is why I'm turning it into a string and trying to unpack it in the new function

testFunction(listString)

def testFunction(oldList):
    print(json.dumps(oldList))

this will print out [{'username': 'userName', 'email': 'email'}] but won't let me return the object from the new function. What do I need to do to fix this?

def testFunction(oldList):
    newList = json.loads(oldList)
    # code to append to newList

    return newList


Response: null
3
  • 1
    Why don't you just use the dictionary that you get from json.loads()? Commented Feb 10, 2019 at 21:57
  • After I'm done appending to the dictionary, I try to return the whole thing but only get null. Sorry I made a typo in my question, I edited it. Commented Feb 10, 2019 at 22:02
  • 1
    Your assertion that "it isn't possible to pass a JSON object directly to another function" is completely false. Python does not restrict you passing any type of object between functions. Commented Feb 10, 2019 at 22:04

1 Answer 1

8

This looks like a homework question - you should make that clear in your question.

I know it isn't possible to pass a JSON object directly to another function

There is no "JSON object" you have a python list that contains a python dictionary. json.dumps turns that list into a JSON string and json.loads(string) takes that string and returns a python list.

You can pass your userList to the function. Or if this is homework and you are required to pass a JSON string you use json.dumps to convert your list to a JSON string first:

import json

userList = [{"username": 'userName', "email": 'email'}]

listString = json.dumps(userList)

def foo(jsonstring):
  lst = json.loads(jsonstring)
  lst[0]["username"] = "Alex"
  return lst

newList = foo(listString)

print(newList)

The output is:

[{'username': 'Alex', 'email': 'email'}]

After your edit I see the problem in your code. Do you see what you did?

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

Comments

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.