Converting Python Dictionary to JSON Array - python

I currently have a Python Dictionary that looks something like this:
OrderedDict([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109), ...
that I am converting to JSON like so:
one_yr = json.dumps(priceDict)
Currently I am adding values to the dictionary from an SQL query by looping through it like so:
for i in query:
date = i[0]
close = i[1]
priceDict[date] = close
The problem is that this returns a JSON object, that i then have to convert to a JSON array.
I am wondering if I can just convert my Python Dictionary to a JSON array directly? Thanks.

json.dumps(list(priceDict.items()))
But why do you have an OrderedDict in first place? If you pass the same list you passed to OrderedDict to json.dumps it will generate your array:
json.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....])
No need for OrderedDict in this case

If you want to convert a Python Dictionary to JSON using the json.dumps() method.
`
import json
from decimal import Decimal
d = {}
d["date"] = "2017-07-24"
d["quantity"] = "149.7619"
print json.dumps(d, ensure_ascii=False)
`

I removed the OrderedDict but kept all the other data, I think I understand the request. See if this works for you:
import json
my_dict = ([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109)])
print(json.dumps(my_dict, indent=4, sort_keys=True))

Related

I want to convert a list of strings to a list of dictionaries

I stored a twitter data to a mysql db as a json. When I fetch it back, it returns a list of string instead of a list of dictionary. I am looking for a way turn it to a list of dictionaries. This is the format i get the stored data back. "tweetdata" is the column name in the db
[{"tweetdata":"[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for
Android\",\"Likes\":0,\"RTs\":0},}]"}]
I want it to return something like this as a list of dicts with the column name stripped off
[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for
Android\",\"Likes\":0,\"RTs\":0},}]
First of all, looks like you provided a wrong json format. Provided that you have a correct json format then you can use json loads function to load the the json data and convert it to dictionary type. Here is code snippet in python.
import json
json_data = '[{"tweetdata":[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0}]}]'
parsed_json = json.loads(json_data)
parsed_dict = parsed_json[0]['tweetdata'][0]
print(type(parsed_dict))
for item in parsed_dict.items():
print(item)
Above code snippet will print these.
<class 'dict'>
('text', 'b problem')
('len', 10)
('Date', 1583160242000)
('Source', 'Twitter for Android')
('Likes', 0)
('RTs', 0)
Try this:
if your data in tweetdata variable then tweetdata[0]["tweetdata"]
it'll return like this:
[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0},}]
actually you can do like this:
data = [{"tweetdata":"[{\"text\":\"b problem\",\"len\":10,\"Date\":1583160242000,\"Source\":\"Twitter for Android\",\"Likes\":0,\"RTs\":0},}]"}][0]["tweetdata"]
and print data you'll get the same result.

Python:Get value of a dictionary present in aTuple

I have a tuple like: t= ({'count': 5L},)
Here i don't want to use for loop but want to get value as 5.Then how can i do it?
I tried with coverting to string then using JSON.
import json
s = str(t)
d = json.loads(s)
I got error:ValueError: No JSON object could be decoded
And winded up with no result.
I want to get the value of count as integer 5 & store in a variable.
Anyone having any idea?
No need to use Json since it is already your tuple is already a Python data structure.
If you know the index of the item in the tuple, and you know the keyname you can access it directly using:
t = ({'count': 5L},)
value = int(t[0]['count'])

Python 3. Extract data from json

How to extract 41677?
My json:
{"41677":{"key":"ilya","premium":"true"}}
My code:
params={"id": "ilya", "fmt": "json"}
r=requests.get("somesite", params=params )
data=json.loads(r.text)
By using loads, your JSON string will be converted to a dictionary which maps keys to values.
Since you need the key 41677, you can simply call data.keys()[0] to retrieve the first key of your dictionary.
EDIT:
Also, if you have a list of that JSON structure, you can iterate over the keys and values using the items function, like so:
for key, value in data.items():
print key # 41677
print value # {"key":"ilya","premium":"true"}
By using Requests' built-in json attribute:
data = requests.get("somesite", params=params ).json().keys()[0]
assuming the json it returns is {"41677":{"key":"ilya","premium":"true"}}:
>>>print data
"41677"
import json
s = {"41677":{"key":"ilya","premium":"true"}}
d = json.dumps(s)
l = json.loads(d)
l.keys()

Parse json data

My data.json is
{"a":[{"b":{"c":{ "foo1":1, "foo2":2, "foo3":3, "foo4":4}}}],"d":[{"e":{"bar1":1, "bar2":2, "bar3":3, "bar4":4}}]}
I am able to list both key/pair values. My code is:
#! /usr/bin/python
import json
from pprint import pprint
with open('data2.json') as data_file:
data = json.load(data_file)
pprint(data["d"][0]["e"])
Which gives me:
{u'bar1': 1, u'bar2': 2, u'bar3': 3, u'bar4': 4}
But I want to display only the keys without any quotes and u like this:
bar1, bar2, bar3, bar4
Can anybody suggest anything? It need not be only in python, can be in shell script also.
The keys of this object are instances of the unicode string class. Given this, the default printing behavior of the dict instance for which they are the keys will print them as you show in your post.
This is because the dict implementation of representing its contents as a string (__repr__ and/or __str__) seeks to show you what objects reside in the dict, not what the string representation of those objects looks like. This is an important distinction, for example:
In [86]: print u'hi'
hi
In [87]: x = u'hi'
In [88]: x
Out[88]: u'hi'
In [89]: print x
hi
This should work for you, assuming that printing the keys together as a comma-separated unicode is fine:
print ", ".join(data["d"][0]["e"])
You can achieve this using the keys member function from dict too, but it's not strictly necessary.
print ', '.join((data["d"][0]["e"].keys()))
data["d"][0]["e"] returns a dict. In python2, You could use this to get the keys of that dict with something like this:
k = data["d"][0]["e"].keys()
print(", ".join(k))
In python3, wrap k in a list like this
k = list(data["d"][0]["e"].keys())
print(", ".join(k))
Even simpler, join will iterate over the keys of the dict.
print(", ".join(data["d"][0]["e"]))
Thanks to #thefourtheye for pointing this out.

How to parse this json using python

I know its kind of trivial thing to ask...but i'm a new bee to python.
Here is a json string
reply = {u'f': [{u'v': u'0'}]}
How to parse out value 0 from it using python.
i tried like
count = reply['rows'][0]['v']
but it not working
count = reply['f'][0]['v'] should work I believe.
reply is a dictionary. As such, you need to use the dictionary keys to access the data. In this case, the key is 'f', not 'rows'.
If you had valid JSON, you could use the simplejson module:
from simplejson import loads, dumps
my_dict = loads(my_json_serialized_string)
and then you can access the python dict, e.g.,:
print my_dict.items()
print my_dict.keys()
print my_dict.values()
#lets assume 'rows' exists as a key, and the value is a list, and the first item of that list is a dict that contains the key 'v':
print my_dict['rows'][0]['v']
and you can even change the dict, and serialize it as a valid JSON string:
my_dict['my_key'] = 'my_value'
my_other_json_serialized_string = dumps(my_dict)

Categories

Resources