user3530656
user3530656

Reputation: 121

How to parameterize JSON object in a Python script

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"?

Upvotes: 2

Views: 4110

Answers (3)

Learner
Learner

Reputation: 5292

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'}}]

Upvotes: 1

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

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')

Upvotes: 0

9000
9000

Reputation: 40884

You can construct proper JSON:

import json

the_value = 'Test'

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

json_text = json.dumps(data)

Upvotes: 3

Related Questions