简体   繁体   中英

how to print after the keyword from python?

i have following string in python

b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'

I want to print the all alphabet next to keyword "name" such that my output should be

waqas 

Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?

First you need to decode the string since it is binary b . Then use literal eval to make the dictionary, then you can access by key

>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'

It is likely you should be reading your data into your program in a different manner than you are doing now.

If I assume your data is inside a JSON file, try something like the following, using the built-in json module:

import json

with open(filename) as fp:
    data = json.load(fp)    
print(data['name'])

You can convert the string into a dictionary with json.loads()

import json
mystring = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
mydict = json.loads(mystring)
print(mydict["name"])
# output 'waqas'

if you want a more algorithmic way to extract the value of name :

s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a",\
"persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],\
"name":"waqas"}'

s = s.decode("utf-8")

key = '"name":"'
start = s.find(key) + len(key)
stop = s.find('"', start + 1)

extracted_string = s[start : stop]
print(extracted_string)

output

waqas

First you need to convert the string into a proper JSON Format by removing b from the string using substring in python suppose you have a variable x :

import json
x = x[1:];
dict = json.loads(x) //convert JSON string into dictionary
print(dict["name"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM