0

We do have this string:

{"transaction_invoiceno":"11111","fallback":false,"emvTags":"null"}

How to convert this string to list or array so we can get values and print them, for example:

transaction_invoiceno = 11111
fallback = false
emvTags = null
np_6
  • 514
  • 1
  • 6
  • 19

4 Answers4

0

You can use the inbuilt json library like this although you need to replace your double quotes with single ones or you'll get an error.

If you want to iterate through the key, value pairs of the dictionary you can simply use the .items() method.

import json

my_json = '{"transaction_invoiceno":"11111","fallback":false,"emvTags":"null"}'
my_dict = json.loads(my_json)

for k,v in my_dict.items():
    print(k, v)

transaction_invoiceno 11111
fallback False
emvTags null
Johnny John Boy
  • 3,009
  • 5
  • 26
  • 50
0

I believe something like the following snippet should do the trick:

s = '{"transaction_invoiceno":"11111","fallback":false,"emvTags":"null"}'
s = s.replace('false', 'False')
exec('d = '+ s)

transaction_invoiceno = int(d["transaction_invoiceno"])
fallback = d["fallback"]
emvTags = d["emvTags"]

However, the null will be a string.

Mimi Lazarova
  • 31
  • 1
  • 2
  • 4
0

One of the best method to resolve this issue is given by User:Johnny John Boy. This is another way check out this code:

my_json = '{"transaction_invoiceno":"11111","fallback":false,"emvTags":"null"}'.replace('false', 'False')
my_dict = eval(my_json)

for k,v in my_dict.items():
    print(k, v)

For more detail you can check out this link

Davinder Singh
  • 2,060
  • 2
  • 7
  • 22
  • It's interesting, I started with this approach and thought it looked like he was doing API stuff so changed my approach :-) I prefer yours – Johnny John Boy Apr 16 '21 at 13:25
0
import json

data = json.loads('{"transaction_invoiceno":"11111","fallback":false,"emvTags":"null"}') 

#
# Get values by key name
#
transaction_invoiceno = data['transaction_invoiceno']
fallback              = data['fallback']
emvTags               = data['emvTags']

#
# Convert data types ("fallback" already set to bool by json.loads)
#
transaction_invoiceno = int(transaction_invoiceno)
emvTags = (None if data['emvTags'] == "null" else data['emvTags']) 

#
# Check types
#
print f"transaction_invoiceno: type: {type(transaction_invoiceno)}, value: {transaction_invoiceno}")
print(f"fallback: type: {type(fallback)}, value: {fallback}")
print(f"emvTags: type: {type(emvTags)}, value: {emvTags}")

IODEV
  • 1,706
  • 2
  • 17
  • 20