Pthomas
Pthomas

Reputation: 355

Convert JSON values into a string

r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'

data = json.loads(r)

for element in data: 
    for value in data['available_sizes']:
        print(value['name'])

At the moment this prints out the following:

40
41
42
43
45

How would I then use this data as a string? Below is the desired output.

Available sizes are 40, 41, 41, 43, 45

Upvotes: 1

Views: 86

Answers (3)

dsal3389
dsal3389

Reputation: 720

Do something like that this is the out put that you want

import json

 r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'

data = json.loads(r)

var = []

for element in data: 
    for value in data['available_sizes']:
        var.append(value['name'])
print( 'Availble size are %s' %(', '.join(var)))

Upvotes: 0

cs95
cs95

Reputation: 402493

Your outermost loop is superfluous, since you only have a single key to iterate over.

Iterate over data, append your numbers to a list, and then call str.join at the end to efficiently join your strings together.

nums = []
for v in data['available_sizes']:
    nums.append(str(v['name']))  # v['name'] if it is already string

print(f'Available sizes are {', '.join(nums)}')

You can rewrite the loop using a list comprehension -

num_str = ', '.join([v['name'] for v in data['available_sizes']])
print(f'Available sizes are {num_str}')  

For a primer on JSON data traversals, I recommend looking at this answer.

Upvotes: 1

Pierre
Pierre

Reputation: 1099

Use a for-comprehension to extract the size names, and then str.join() to add the comma separator:

import json

r = '{"available_sizes":[{"id":104682,"name":"40","preorder_only":false},{"id":104683,"name":"41","preorder_only":false},{"id":104684,"name":"42","preorder_only":false},{"id":104685,"name":"43","preorder_only":false},{"id":104687,"name":"45","preorder_only":false}]}'
data = json.loads(r)

# Extract the size names from the list of available sizes
size_names = [size_entry["name"] for size_entry in data["available_sizes"]]

# Join the sizes names as strings using a comma separator and print
sizes_string = ", ".join(size_names)
print("Available sizes are: " + sizes_string)

Upvotes: 0

Related Questions