Joko Joko
Joko Joko

Reputation: 121

How to convert JSON string values to lowercase in Python?

Have been struggling now couple hours to lowercase objects with Python. To use str lowercase function I need to convert it to the string. Can I someway convert it back to JSON? Because now there is just three objects in list which are strings.

My code:

from fastapi import FastAPI, Query, Depends
from typing import Optional, List

robots = [
    {'name': 'ABB', 'short': 'ABB'},
    {'name': 'Techman Robots', 'short': 'TM'},
    {'name': 'Mobile Industry Robots', 'short': 'MIR'},
]

@app.get('/robots')
def get_courses(lower: Optional[int] = None):
    cs = robots

    if lower == 1:
        cs = []
        for c in robots:
            joku = str(c).lower()
            cs.append(joku)

    return {'Robots': cs}

I want the results be like this:

    {'name': 'abb', 'short': 'abb'},
    {'name': 'techman robots', 'short': 'tm'},
    {'name': 'mobile industry robots', 'short': 'mir'},

I hope you understand what I mean. Sorry little language barrier. Thanks guys.

Upvotes: 0

Views: 3353

Answers (2)

Abhi_J
Abhi_J

Reputation: 2129

robots is a list of dictionaries, so try the following

  1. Iterate over dictionaries in the list robots
  2. Iterate over keys in each dictionary
  3. Get value of each key in dictionary, convert them to lowercase using .lower()
  4. Save key and value in a new dictionary, append it to the new list

This should do it:

robots = [
    {'name': 'ABB', 'short': 'ABB'},
    {'name': 'Techman Robots', 'short': 'TM'},
    {'name': 'Mobile Industry Robots', 'short': 'MIR'},
]

new_robots = []

for mdict in robots:
  new_dict = {}
  for key, value in mdict.items():
    new_dict[key] = value.lower()
  new_robots.append(new_dict)

print(robots)

or in one line

new_robots = [{key: value.lower() for key, value in mdict.items()} for mdict in robots]

Output:

[{'name': 'abb', 'short': 'abb'}, {'name': 'techman robots', 'short': 'tm'}, {'name': 'mobile industry robots', 'short': 'mir'}]

Upvotes: 3

Joko Joko
Joko Joko

Reputation: 121

Got this working with ast:

import ast

@app.get('/robots')
def get_courses(lower: Optional[int] = None): 
    cs = robots

    if lower == 1:
        cs = []
        for c in robots:
            finallyWorking= ast.literal_eval(str(c).lower())
            cs.append(finallyWorking) 

    return {'Robots': cs}

Upvotes: 0

Related Questions