1

I am controlling a smart light bulbs and publishing their status in UI dashboard, as a status I am getting a string data of "ON" and "OFF", but instead of this string data I want to get an integer data of 1 and 0, is there anyway I can convert this string data into integer data using JSON module in Python Dictionary.

Some of The API code of my smart Bulbs is here:

 if (_deviceUrl.getcode() == 200):
     data = _deviceUrl.read().decode("utf-8")
     # Use the json module to load the string data into a dictionary
     _theJSON = json.loads(data)
     # 1. status
     devicedata['on'] = self.on_dict[_theJSON["action"]['on']]
     # 2. brightness convert to %
     devicedata["bri"] = int(round(float(_theJSON["action"]["bri"]) * 100 / 255, 0))
1
  • The usual way is to use the int() function: i.e. int("123") -> 123. Commented Dec 19, 2018 at 7:29

2 Answers 2

1

You can use following construction:

devicedata["on"] = 1 if _theJSON["action"]["on"] == "ON" else 0

It's pretty self-explanatory.

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

Comments

0

One way to replace a string with an integer like that is to define a separate dictionary:

ints = { 'OFF': 0, 'ON': 1 }

So for example if the value of d['action']['status'] is the string "ON", then ints[d['action']['status']] returns the integer 1.

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.