I'm trying to convert an string into json output from local Data or Those datas from BeautifulSoup output as Json.for example:
#! /usr/bin/python
data = ('Hello')
print data
and i need to convert this Hello as json output.
How can do that?
is this possible?
Check out the json module in Python https://docs.python.org/2/library/json.html
import json
json.dumps({"hello": 0}, sort_keys=True)
You can use the json module to encode Python objects as JSON, e.g.
>>> import json
>>> data = ('Hello')
>>> json.dumps(data)
'"Hello"'
>>> data = ('Hello', 'There')
>>> json.dumps(data)
'["Hello", "There"]'
>>> data = {'message': 'Hello'}
>>> json.dumps(data)
'{"message": "Hello"}'
Related
I'm trying to parse the test_string to JSON but failing, just continues as string after json.dumps, see result below. How can I get the expected output?
The test_string is pulled from a text object and that's how it's quoted.
test_string = "{'fruit': ['Yes'], 'vegetables': ['carrot']}"
# output
json.dumps(test)
'"{\'fruit\': [\'Yes\'], \'vegetables\': [\'carrot\']}"'
# expected output
{'fruit': ['Yes'], 'vegetables': ['carrot']}
use ast and json
import ast
import json
data = ast.literal_eval("{'fruit': ['Yes'], 'vegetables': ['carrot']}")
print(json.dumps(data))
output
{"fruit": ["Yes"], "vegetables": ["carrot"]}
json.loads() should do the trick
test_string = "{'fruit': ['Yes'], 'vegetables': ['carrot']}"
new_test_string = json.loads(test_string)
In python, I can use the below code to dynamically create IP address array to store n number of IP addresses.
for i in range(12):
addr[i] = "10.1.1." + str(i)
print addr[i]
I want a similar code for JSON file. Is it possible to define variables with looping in JSON file?
You don't "loop over a json file" - this makes no sense actually. You create a json string representation of a Python object - usually a dict - and eventually write it to a file (or send it as HTTP response content etc), or create a Python object from a json string:
>>> import json
>>> addr = ["10.1.1.{}".format(i) for i in range(12)]
>>> print(repr(json.dumps(addr)))
'["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"]'
>>> print(repr(json.dumps({"addr": addr})))
'{"addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"]}'
If you have an existing json string (from a file or any other source) and want to update it, you just parse it (with json.loads) to a Python object, update the python object, and dump it back to json. Assuming you have the following json string (either from a file, http response or whatever, doesn't matter):
>>> source = '{"foo": "bar", "addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2"]}'
and you want to change "foo"'s value to "baaz", add addresses up to 10.1.1.11 and add a "frobnicate: true" key=>value pair:
>>> import json
>>> data = json.loads(source)
>>> data["foo"] = "baaz"
>>> for i in range(12):
... ip = "10.1.1.{}".format(i)
... if ip not in data["addr"]:
... data["addr"].append(ip)
...
>>> data["frobnicate"] = True
>>> updated_json = json.dumps(data)
>>> print(repr(updated_json))
'{"foo": "baaz", "addr": ["10.1.1.0", "10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.4", "10.1.1.5", "10.1.1.6", "10.1.1.7", "10.1.1.8", "10.1.1.9", "10.1.1.10", "10.1.1.11"], "frobnicate": true}'
>>>
I have a very huge unicode JSON data of the following format
{u'completed': True, u'entries': [{u'absolute_time':
u'2017-05-17T10:41:52Z', u'command': None, u'level':
u'NORMAL',......
It has Json objects within JSON objects. Unable to read it and parse it due to the encoding. Tried the following code.
Could someone please tell how to parse it and convert it to a normal JSON object.
with open(r"inp.json", 'r') as jsonData:
jsonToPython = json.load(jsonData) #gives error here itself
#jsonData = ast.literal_eval(jsonData)
print(json.dumps(jsonToPython))
#print (jsonToPython)
You can try to load the (stringified) python object using ast:
>>> #obj = open(r"inp.json", 'r').read()
>>> obj = "{u'completed': True, u'entries': [{u'absolute_time': u'2017-05-17T10:41:52Z'}]}"
>>> ast.literal_eval(obj)
{'completed': True, 'entries': [{'absolute_time': '2017-05-17T10:41:52Z'}]}
>>>
I have a dictionary:
data = {"data": "\u512b"}
while I dump that to json:
import json
print json.dumps(data)
I got:{"a":"\\u512b"}
What should I do to get exactly {"a":"\u512b"}?
NOTE: I try to add u before the string so it becomes u'\u512b' and the extra \ won't show up again, please also tell me why
You can do some hacking.
import json
data = {"data": "\u512b"}
s = json.dumps(data)
print(s.replace(r'\u', 'u'))
print(type(s.replace(r'\u', 'u')))
Output:
{"data": "\u512b"}
<type 'str'>
My guess is that you are just confused by the output of the Python interpreter, displaying you the json.dumps generated string with its own \ escape character prepended to the \ character in the string. The JSON string as a value contains exactly one \, as you want (IIUC):
>>> data = {"data": "\u512b"}
>>> data
{'data': '\u512b'}
>>> import json
>>> json.dumps(data)
'{"data": "\\u512b"}'
>>> print(json.dumps(data))
{"data": "\u512b"}
>>> json.dump(data, open('data.json', 'w'))
>>> ^Z
C:\opt\Console2>type data.json
{"data": "\u512b"}
This is entirely independent of JSON in fact, as the following example shows:
>>> s = "s\\u"
>>> s
's\\u'
>>> print(s, len(s)) # length of s is 3, not 4
s\u 3
HTH!
I want to convert such query string:
a=1&b=2
to json string
{"a":1, "b":2}
Any existing solution?
Python 3+
import json
from urllib.parse import parse_qs
json.dumps(parse_qs("a=1&b=2"))
Python 2:
import json
from urlparse import parse_qs
json.dumps(parse_qs("a=1&b=2"))
In both cases the result is
'{"a": ["1"], "b": ["2"]}'
This is actually better than your {"a":1, "b":2}, because URL query strings can legally contain the same key multiple times, i.e. multiple values per key.
>>> strs="a=1&b=2"
>>> {x.split('=')[0]:int(x.split('=')[1]) for x in strs.split("&")}
{'a': 1, 'b': 2}
Python 3.x
from json import dumps
from urllib.parse import parse_qs
dumps(parse_qs("a=1&b=2"))
yelds
{"b": ["2"], "a": ["1"]}
dict((itm.split('=')[0],itm.split('=')[1]) for itm in qstring.split('&'))