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
2
  • You are using double quote inside a string which is enclosed using double quote, which is wrong. Is it a file or a string? Commented Apr 16, 2021 at 12:58
  • You can try using d = json.loads(your_string). After this you can access your variable using d['transaction_invoiceno'] Commented Apr 16, 2021 at 12:59

4 Answers 4

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.

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

Comments

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

1 Comment

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

Comments

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}")

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.