I am using python 3.10.4. I have a string which is as follows:
str_obj = "[(190229461780583, 'main'), (302030571463836, 'feature/BRANCH_livestream'), (1071064128966159, 'feature/BRANCH_sensitive'), (1137211553786277, 'main'), (1283366887974580, 'feature/add_sql_vm'), (1492751472739439, 'feature/BRANCH-2977'), (2662272892040840, 'main'), (4078787696930326, 'main')]"
I need to convert it to a json object. I need it in json format for further data extraction. Following this link I used json.loads() to convert it from string to json:
json_obj = json.loads(str_obj)
However I am getting the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I checked this link but it is not really related to my problem.
I cannot simply drop "" from str_obj as this is the value I am receiving from an environment variable sent to me from a DevOps pipeline.
I would like to know what the root cause problem is and how I can resolve it.
CodePudding user response:
Probably something like this would help you if you wanted to make json out of this string. Surely the best option would be to fix the input data
str_obj = "[(190229461780583, 'main'), (302030571463836, 'feature/BRANCH_livestream'), (1071064128966159, 'feature/BRANCH_sensitive'), (1137211553786277, 'main'), (1283366887974580, 'feature/add_sql_vm'), (1492751472739439, 'feature/BRANCH-2977'), (2662272892040840, 'main'), (4078787696930326, 'main')]"
# clear the input string
str_obj = str_obj.replace('[','').replace(']','').replace('(','').replace(')','').replace('\'','').replace(' ','').split(',')
# create output string
output = {}
# Create pairs of key:value
str_to_list = [str_obj[i:i 2] for i in range(0, len(str_obj), 2)]
# append to output dict
for e in str_to_list:
output[e[0]] = e[1]
# You can easly create json form dict
json_object = json.dumps(output)
CodePudding user response:
That isn't json, json uses key value pairs. Did you want ast.literal_eval
?
import ast
ast.literal_eval(str_obj)
# [(190229461780583, 'main'), (302030571463836, 'feature/BRANCH_livestream'), (1071064128966159, 'feature/BRANCH_sensitive'), (1137211553786277, 'main'), (1283366887974580, 'feature/add_sql_vm'), (1492751472739439, 'feature/BRANCH-2977'), (2662272892040840, 'main'), (4078787696930326, 'main')]
CodePudding user response:
The value of your str_obj
is simply not a valid json format at all. You can use a JSON parser online to verify the syntax you need to turn into a valid JSON : Online JSON parser