Let's say I want to create a json object following the structure:
{"favorite_food":["icecream","hamburguers"]}
to do so in python, if i know the whole string in advance, I can just do:
json.dumps({"favorite_food":["icecream","hamburguers"]})
which works fine.
my question though is, how would i do the same thing if i wanted to get the object as a result of a string interpolation? For example:
favorite food = 'pizza'
json.dumps({"favorite_food":[%s]}) %favorite_food
the issue i found is, if I do the interpolation prior to calling the json.dumps:
dict= '{"favorite_food":[%s]}' % favorite_food
if i then do json.dumps(dict) , because of the string quotation, the json_dumps returns:
{"favorite_food":[pizza]}
that is, is not a dict anymore (but a string with the structure of a dict)
How can i solve this simple issue?
Why not just:
>>> food = "pizza"
>>> json.dumps({"favorite_food":[food]})
'{"favorite_food": ["pizza"]}'
json,dumps takes actual values as input --- that is, real dicts, lists, ints, and strings. If you want to put your string value in the dict, just put it in. You don't want to put in a string representation of it, you want to put in the actual value and let json.dumps make the string representation.
How about below:
favorite_food = 'pizza'
my_dict = {"favorite_food":[favorite_food]}
print json.dumps(my_dict)
I found this is very simple.
Related
This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 5 months ago.
Well, I am using python. And I have case here.
from my api. The following key and value is coming.
games : ["['football','cricket']"]
Now i want to get that football and cricket from coming games value and store in python list.
expected output:
print(games) ==> ["football","circket"]
print(type(games)) ==> <class list>
Perhaps ast.literal_eval function would be useful here. Just pass the string into the function and a list of strings will be returned.
This will be more robust that trying to manipulate the string, as the function is designed to ingest (if you will) key Python data structures as strings; perform a bit of validation to ensure the string is not malicious, and output the associated object.
Docs linked here
Source code linked here
For example:
import ast
games = ["['football','cricket']"]
ast.literal_eval(games[0])
Output:
['football','cricket']
this should work
a = ["['football','cricket']"]
out = [val.strip("'") for val in a[0].strip("[|]").split(",")]
print(out)
['football', 'cricket']
I find it unlikely that a api is sending a non-json string. This string is not json because of the single quotes. If you convert them to double quotes, you have a valid json.
list_games = json.loads(games[0].replace("'",'"'))
This question already has an answer here:
Why does printing a tuple (list, dict, etc.) in Python double the backslashes?
(1 answer)
Closed 7 months ago.
When I create a string containing backslashes, they get duplicated:
NOTE : I want to add \ in request because i want to call third party API and they want me to send request with \ in some of their keys.
I have taken reference from this answer Why do backslashes appear twice?, but its working only for string, not for dict.
mystr = {"str": "why\does\it\happen?"}
print(mystr)
output:
{'str': 'why\\does\\it\\happen?'}
here i am attching a screenshot for better understanding.
mystr isn't a str, it's a dict. When you print a dict, it prints the repr of each string inside it, rather than the string itself.
>>> mydict = {"str": "why\does\it\happen?"}
>>> print(mydict)
{'str': 'why\\does\\it\\happen?'}
>>> print(repr(mydict['str']))
'why\\does\\it\\happen?'
>>> print(mydict['str'])
why\does\it\happen?
Note that the repr() includes elements other than the string contents:
The quotes around it (indicating that it's a string)
The contents use backslash-escapes to disambiguate the individual characters. This extends to other "special" characters as well; for example, if this were a multiline string, the repr would show linebreaks as \n within a single line of text. Actual backslash characters are always rendered as \\ so that they can be distinguished from backslashes that are part of other escape sequences.
The key thing to understand is that these extra elements are just the way that the dict is rendered when it is printed. The actual contents of the string inside the dict do not have "doubled backslashes", as you can see when you print mydict['str'].
If you are using this dict to call an API, you should not be using str(mydict) or anything similar; if it's a Python API, you should be able to use mydict itself, and if it's a web API, it should be using something like JSON encoding (json.dumps(mydict)).
I think that to build the printed string of the dict, python call the __repr__ method of object inside it (for the values) instead of the __str__ as you would expect for printing the dict.
It would make sense since dict can contain every type of object not just string so the __repr__| method can be found everywhere (it's included in the base object in python) when the __str__ need to be written.
But it's only a guess, not a definitive answer.
I am writing a code where I am facing the problem and need a solution if it exists.
Suppose we have a following String type variable in Python which contains an integer value.
Eg:x='123'
I know that we can easily convert this by type conversion to int.
However, suppose we have the following list.
x=['123','Spain']
Is there any method in Python by which I can know which element of the list x is Integer contained inside a string and which is purely an Object?
I would recommend this method:
x = "123"
if x.isdigit():
# int
elif x.replace(".","",1).isdigit():
# float
else:
# str
I assume you have similar question with this post.
But, from my perspective, for more general solution (language agnostic), you should learn more about Regular Expression, here also the same question
I have a long string that almost looks like a dictionary. I want to convert this to a proper Python dictionary. An example of the string is below:
'{"autorunResult":"0","batteryInfo":"No system battery","cpuBrand":"Intel(R) Xeon(R) CPU E5-1650 v3 # 3.50GHz","id":"bMlXyTrjXOOo","localeId":"1033","numCores":"1","payloadResult":"0","processorArchitecture":"x64 (AMD or Intel)","systemMemory":"0.2 GB","v":"5","windowsVersion":"Windows 7 Service Pack 1","payloadSaved":true,"autorunSaved":true,"installedApps":["AddressBook","Adobe AIR","com.adobe.mauby.4875E02D9FB21EE389F73B8D1702B320485DF8CE.1","Connection Manager","DirectDrawEx","Fontcore","IE40","IE4Data","IE5BAKEX","IEData","MobileOptionPack","Pillow-py2.7","SchedulingAgent","WIC","{00203668-8170-44A0-BE44-B632FA4D780F}","{26A24AE4-039D-4CA4-87B4-2F83217000FF}","{32A3A4F4-B792-11D6-A78A-00B0D0170000}","{4A03706F-666A-4037-7777-5F2748764D10}","{77DCDCE3-2DED-62F3-8154-05E745472D07}","{AC76BA86-7AD7-1033-7B44-A90000000001}","{BB8B979E-E336-47E7-96BC-1031C1B94561}","{C3CC4DF5-39A5-4027-B136-2B3E1F5AB6E2}"],"autoRunApps":["OptionalComponents","Adobe Reader Speed Launcher","SunJavaUpdateSched","MFDS"]}'
Note that this looks like a string representation of a dictionary. In fact, it is not. These two k,v pairs kill it: "payloadSaved":true,"autorunSaved":true. (no double-quotes around the values).
Basically, I need to take the long input string and convert it to a dictionary. Any tricks?
I tried:
using ast.literal_eval. It bombs...because of the above issue. Need to somehow sanitize the input string so that ast works.
Take out the parenthesis, tokenize the long string on comma, but again, it bombs...(the list values have commas...).
Not sure how to proceed.
If that is JSON, then:
import json
d = json.loads(s)
If that is Python file:
d = eval(s)
For the string keys & values you will find no much difference. The difference may appear when true/True or false/False or null/None values appear, or on how the lists/dicts are serialized in some cases.
I'm trying to insert a unix timestamp using REST to a webservice. And when I convert the dictionary I get the value: 1392249600000L I need this value to be an integer.
So I tried int(1392249600000L) and I get 1392249600000L, still a long value.
The reason I need this is because the JSON webservice only accepts timestamsp with milliseconds in them, but when I pass the JSON value with the 'L' in it I get an invalid JSON Primative of value 1392249600000L error.
Can someone please help me resolve this? It seems like it should be so easy, but it's driving me crazy!
You should not be using Python representations when you are sending JSON data. Use the json module to represent integers instead:
>>> import json
>>> json.dumps(1392249600000L)
'1392249600000'
In any case, the L is only part of the string representation to make debugging easier, making it clear you have a long, not int value. Don't use Python string representations for network communications, in any case.
For example, if you have a list of Python values, the str() representation of that list will also use repr() representations of the contents of the list, resulting in L postfixes for long integers. But json.dumps() handles such cases properly too, and handle other types correctly too (like Python None to JSON null, Python True to JSON true, etc.):
>>> json.dumps([1392249600000L, True, None])
'[1392249600000, true, null]'