Home > Mobile >  Parse values in python
Parse values in python

Time:12-04

I have to parse some text and extract it in variables

Example: {'ID': '1', 'name': 'John', 'lname': 'Wick'} to

ID = 1
name = 'John'
lname = 'Wick'

CodePudding user response:

One way is to use yaml.safe_load:

import yaml

d = "{'ID': '1', 'name': 'John', 'lname': 'Wick'}"
out = yaml.safe_load(d)

Output:

{'ID': '1', 'name': 'John', 'lname': 'Wick'}

CodePudding user response:

To parse the text and extract the values into separate variables, you can use the Python built-in json module. Here's an example of how you could do this:

import json

# Define the text you want to parse
text = '{"ID": "1", "name": "John", "lname": "Wick"}'

# Use the json.loads() method to parse the text and convert it into a Python dictionary
data = json.loads(text)

# Extract the values from the dictionary and assign them to separate variables
ID = data["ID"]
name = data["name"]
lname = data["lname"]

# Print the values to verify that they were extracted correctly
print(ID)    # Output: 1
print(name)  # Output: John
print(lname) # Output: Wick

Alternatively, you could use the Python built-in eval() function to evaluate the text as a Python expression and convert it directly into a dictionary, like this:

# Define the text you want to parse
text = '{"ID": "1", "name": "John", "lname": "Wick"}'

# Use the eval() function to convert the text into a dictionary
data = eval(text)

# Extract the values from the dictionary and assign them to separate variables
ID = data["ID"]
name = data["name"]
lname = data["lname"]

# Print the values to verify that they were extracted correctly
print(ID)    # Output: 1
print(name)  # Output: John
print(lname) # Output: Wick

Note that using the eval() function to parse arbitrary text can be dangerous, as it can potentially allow malicious code to be executed. It is generally better to use the json.loads() method instead, as it is safer and more reliable.

  • Related