Converting dictionary string to dictionary failed - python

I tried to convert below string to dictionary by json.loads() and ast.literal_eval method but both failed, please kindly help:
text = '{"data":{"FormId":"BD_Rate","TopRowCount":0,"Limit":0,"StartRow":0,"FilterString":'',"OrderString":'',"FieldKeys":"FRateID,FDocumentStatus,FForbidStatus,FName,FDescription,FCreateOrgId,FUseOrgId,FCreatorId,FModifierId,FCreateDate,FModifyDate,FBegDate,FCyToID,FEndDate,FRATETYPEID,FCyForID,FAuditDate,FAuditorID,FForbidderID,FForbidDate,FIsSysPreset,FExchangeRate,FReverseExRate"}}'

Your string is quoted using single quotes (') and you also have "OrderString":'' as part of your string. Python will remove those '' because it will assume string concatenation. For example:
s = 'foo''bar'
is equivalent to
s = 'foo' + 'bar'
hence the same thing as
s = 'foobar'
Change your first line to
text = '{"data":{"FormId":"BD_Rate","TopRowCount":0,"Limit":0,"StartRow":0,"FilterString":"","OrderString":"","FieldKeys":"FRateID,FDocumentStatus,FForbidStatus,FName,FDescription,FCreateOrgId,FUseOrgId,FCreatorId,FModifierId,FCreateDate,FModifyDate,FBegDate,FCyToID,FEndDate,FRATETYPEID,FCyForID,FAuditDate,FAuditorID,FForbidderID,FForbidDate,FIsSysPreset,FExchangeRate,FReverseExRate"}}'
and both json and ast.literal_eval will work.

Related

Converting backslash single quote \' to backslash double quote \" for JSON

I've got a JSON file that was converted to a string in Python. Somehow along the way the double quotes have gotten replaced with single quotes.
{\'MyJSON\': {\'Report\': \'1\' ....
I need to convert my string so that it is in this format instead:
{\"MyJSON\": {\"Report\": \"1\" ....
My problem is that using str.replace, I can't figure out how to convert a single quote into a double quote as both quotes are escaped.
My ultimate goal is to be able to put the string into json.loads so that I can pretty print it.
Attempts:
txt.replace(r"\'", r'\"')
> "{'MyJSON': {'Report': '1'"
txt.replace("\"", "\'")
> "{'MyJSON': {'Report': '1'"
If I save my string to a txt file it appears in the preview as:
{'MyJSON': {'Report': '1' ...
So I think what I actually need to do is replace ' with "
I have decided to use ast.literal_eval(txt) which can convert my string to a dictionary. From there, json.loads(json.dumps(dict)) gets me to JSON
i mean,
my_string = "\"\'"
print(my_string.replace("\'", "\""))
works perfectly fine
EDIT: i didn't mean use this directly, it was a proof of concept. In mine the replacement was reversed. I have updated this snippet such that it could directly be put into your code. Try it again
Instead of focusing on the backslashes to try to "hack" a json string / dict str into a JSON, a better solution is to take it one step at a time and start by converting my dict string into a dictionary.
import ast
txt = ast.literal_eval(txt) # convert my string to a dictionary
txt = json.loads(json.dumps(txt)) # convert my dict to JSON

Can't replace a string with multiple escape characters

I am having trouble with the replace() method. I want to replace some part of a string, and the part which I want to replace consist of multiple escape characters. It looks like something like this;
['<div class=\"content\">rn
To remove it, I have a block of code;
garbage_text = "[\'<div class=\\\"content\\\">rn "
entry = entry.replace(garbage_text,"")
However, it does not work. Anything is removed from my complete string. Can anybody point out where exactly I am thinking wrong about it? Thanks in advance.
Addition:
The complete string looks like this;
"['<div class=\"content\">rn gitar calmak icin kullanilan minik plastik garip nesne.rn </div>']"
You could use the triple quote format for your replacement string so that you don't have to bother with escaping at all:
garbage_text = """['<div class="content">rn """
Perhaps your 'entry' is not formatted correctly?
With an extra variable 'text', the following worked in Python 3.6.7:
>>> garbage_text
'[\'<div class=\\\'content\'\\">rn '
>>> text
'[\'<div class=\\\'content\'\\">rn And then there were none'
>>> entry = text.replace(garbage_text, "")
>>> entry
'And then there were none'

Python search string for two numbers, assign to variables

I have the following string a part of a file with lines with the same format.
CONST robtarget robttarget1:=[[-42277.480909368,-4997.36320197,2332.380745999],[0.347787091,-0.799426288,0.217080241,0.439133144],[0,0,0,0],[-35700.0,180.0,2200.000095367,0,9E9,9E9]];
I need to access two specific numbers and preform math on them. -35700.0 and 180.0.
I am struggling with getting those specific values and assign them to variables.
Just get rid of the part of the lines that are not the value and use eval to get the rest as a python variable.
The following line will break your string at the '=' character using split (so you will get 2 strings).
It will then get the second part of your string (the one which starts after the '='), remove the final ';' character and use eval to interpret the whole thing:
result = eval(s.split('=')[1][:-1])
Now you'll get a list of lists that you can extract your numbers from easily
You can split the string by the "=" and then use the ast module to convert the string list to a python list object and the use list indexing to fetch the required value
EX:
import ast
A = "CONST robtarget robttarget1:=[[-42277.480909368,-4997.36320197,2332.380745999],[0.347787091,-0.799426288,0.217080241,0.439133144],[0,0,0,0],[-35700.0,180.0,2200.000095367,0,9E9,9E9]];"
A = A.split("=")[1].replace(";", "") #Remove any non python string.
A = ast.literal_eval(A) #Convert string object to list object
print A[-1][0:2] # I have used slice to fetch the required value
Output:
[-35700.0, 180.0]

Python output a json style string

here defining a variable:
sms_param = '{\"website\":\"hello\"}'
and it print out ok like this : {"website":"hello"}, but i want to pass a dynamic value to its value, so its format should like this: {\"website\":\"{0}\"}.format(msg), but it output a KeyError, I have no idea of this Error, and change all kinds of string format such as triple quotation and change {0} with %s, but all seems useless. how can i solve it.
My suggestion is using json.loads()
>>> sms_param = '{\"website\":\"hello\"}'
>>> import json
>>> json.loads(sms_param)
{'website': 'hello'}
What you can do is using json.loads() convert the json string to dictionary and then change the value, finally convert it back to string

String Delimiter in Python

I want to do split a string using "},{" as the delimiter. I have tried various things but none of them work.
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
Split it into something like this:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
string.split("},{") works at the Python console but if I write a Python script in which do this operation it does not work.
You need to assign the result of string.split("},{") to a new string. For example:
string2 = string.split("},{")
I think that is the reason you think it works at the console but not in scripts. In the console it just prints out the return value, but in the script you want to make sure you use the returned value.
You need to return the string back to the caller. Assigning to the string parameter doesn't change the caller's variable, so those changes are lost.
def convert2list(string):
string = string.strip()
string = string[2:len(string)-2].split("},{")
# Return to caller.
return string
# Grab return value.
converted = convert2list("{1,2},{3,4}")
You could do it in steps:
Split at commas to get "{...}" strings.
Remove leading and trailing curly braces.
It might not be the most Pythonic or efficient, but it's general and doable.
I was taking the input from the console in the form of arguments to the script....
So when I was taking the input as {{2,4,5},{1,9,4,8,6,6,7},{1,2,3},{2,3}} it was not coming properly in the arg[1] .. so the split was basically splitting on an empty string ...
If I run the below code from a script file (in Python 2.7):
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
print string.split("},{")
Then the output I got is:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3 ']
And the below code also works fine:
string="2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3 "
def convert2list(string):
string=string.strip()
string=string[:len(string)].split("},{")
print string
convert2list(string)
Use This:
This will split the string considering },{ as a delimiter and print the list with line breaks.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
for each in string.split('},{'):
print each
Output:
2,1,6,4,5,1
8,1,4,9,6,6,7,0
6,1,2,3,9
2,3,5,4,3
If you want to print the split items in the list only you can use this simple print option.
string = "2,1,6,4,5,1},{8,1,4,9,6,6,7,0},{6,1,2,3,9},{2,3,5,4,3"
print string.split('},{')
Output:
['2,1,6,4,5,1', '8,1,4,9,6,6,7,0', '6,1,2,3,9', '2,3,5,4,3']
Quite simply ,you have to use split() method ,and "},{" as a delimeter, then print according to arguments (because string will be a list ) ,
like the following :
string.split("},{")
for i in range(0,len(string)):
print(string[i])

Categories

Resources