Home > Mobile >  Converting dictionary string to dictionary failed
Converting dictionary string to dictionary failed

Time:11-25

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"}}'

CodePudding user response:

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