2

I am writing a test in Python where i am specifying the JSON sting in a parameter as follows :

json = '...[{"MemberOperand":{
                 "AttributeName":"TEST",
                 "Comparison":"=",
                 "Value":"Test"}
           }]...'

In this example i have the value as "Test" however i want to run the test with several values. Could you guys tell me how can i parameterize The values of "Value"?

2
  • Did the json string come from some place else? One usually updates python objects and then jsonizes. If you don't control the source of the json, you could dump, modify and load again. Commented Dec 14, 2015 at 6:51
  • @tdelaney No, i'm directly passing the whole json string. Commented Dec 14, 2015 at 8:58

3 Answers 3

3

You can construct proper JSON:

import json

the_value = 'Test'

data = [{"MemberOperand": {
    "AttributeName":"TEST",
    "Comparison":"=",
    "Value": the_value}
}]

json_text = json.dumps(data)
Sign up to request clarification or add additional context in comments.

Comments

1

This is regular dictionary (nested) formatted as string -

def changer(x):
    import json
    d=json.loads(json.loads(json.dumps('[{"MemberOperand":{"AttributeName":"TEST","Comparison":"=","Value":"Test"}}]')))
    d[0]['MemberOperand']['AttributeName']=x
    return d
print changer('New_TEST')

Output-

[{'MemberOperand': {'Comparison': '=', 'AttributeName': 'New_TEST', 'Value': 'Test'}}]

Comments

0

Add function which return you different json string all the time by provided value as parameter:

def get_mock_json(value='Test'):
    return '...[{"MemberOperand":{"AttributeName":"TEST","Comparison":"=","Value":%s}}]...'%value


print get_mock_json('test')
print get_mock_json('ttttttest')

3 Comments

That doesn't work because the json curly brackets are interpreted by format.
Changing to %s dodges one bullet but puts you in line with another... what if the json includes a %s in its text?
that's just for test execution purposes...sure, we could make string interpolation with dict, like that one "(value)%s"%{'value': value}

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.