I have a some variables that I need to dump as a json of the format:
{
"elements":[
{
"key":"foo",
"value":"7837"
},
{
"key":"bar",
"value":"3423"
}
]
}
I am trying to figure out the right object which would give the above structure upon usin json.dumps(). I see that in python, lists give a json array where as dictionaries give a json object while using json dumps.
I am trying something like:
x={}
x["elements"]={}
x["elements"]["key"]="foo"
x["elements"]["value"]="7837"
x["elements"]["key"]="bar"
x["elements"]["value"]="3423"
json_x=json.dumps(x)
But this still gives me:
{"elements": {"key": "bar", "value": "3423"}}
which is obviously incorrect.
How to I incorporate the correct dictionary and list structure to get to the above json?
Why don't you just use literal?
x = {
"elements": [
{"key":"foo", "value":"7837"},
{"key":"bar", "value":"3423"}
]
}
To fix your code, you need to use a list literal ([]) when assigning to elements dictionary entry:
>>> x = {}
>>> x["elements"] = [] # <---
>>> x["elements"].append({})
>>> x["elements"].append({})
>>> x["elements"][0]["key"]="foo"
>>> x["elements"][0]["value"]="7837"
>>> x["elements"][1]["key"]="bar"
>>> x["elements"][1]["value"]="3423"
>>> json.dumps(x)
'{"elements": [{"value": "7837", "key": "foo"}, {"value": "3423", "key": "bar"}]}'
But, it's hard to read, maintain.
Related
I would like to know if there is any pythonic way of replacing all arguments (of all strings) that exist in a dictionary with .format. For example:
dictionary = {"name": "{name_user}", "age": 26, "infos": [ {"name": "{name_user}" }]}
information = {"name_user": "Joao"}
Different from the following:
dictionary["name"] = dictionary["name"].format(**information)
dictionary["infos"][0]["name"] = dictionary["infos"][0]["name"].format(**information)
I wonder if there is any more efficient way to do this.
Note: the dictionary would be a JSON file
Here is another way of doing this
information = {"name_user": "Joao"}
dictionary = {
"name": information.get("name_user", ""),
"age": 26,
"infos": [
{
"name": information.get("name_user", "")
}]
}
I don't know if it is most efficient way but I think is more simple way.
I'm new to Python and I'm trying to process something and having no luck finding the answer or if it's already been asked. I'm making a call to an API and receiving some data back as JSON. I'm stripping out certain bits that I don't need with the keys being stripped out and only the values remaining which wouldn't be a problem but I can't get into them as the keys I want to access are nested in an array.
I've been accessing the data and can get up to json.dumps(payload['output']['generic']) but I can't seem to find any information online as to how I can access these last values only.
Apologies in advance if this question already exists.
{
"output": {
"generic": [
{
"response_type": "text",
"text": "hi"
}
],
"intents": [
{
"intent": "CollectionDate",
"confidence": 0.8478035449981689
}
],
"entities": [
{
"entity": "Payslip",
"location": [
19,
26
],
"value": "When is my collection date",
"confidence": 1
}
]
},
"context": {
"global": {
"system": {
"turn_count": 10
}
},
"skills": {
"main skill": {
"user_defined": {
"DemoContext": "Hi!"
},
"system": {}
}
}
}
}
To clarify:
I want to access the "text", "intent" and "confidence"
at the moment I'm printing the value posted and then the responses for the sections I want like the below.
print(x)
print(json.dumps(payload['output']['generic']))
print(json.dumps(payload['output']['intents']))
Use following code to convert the json to a dict first:
json_data = json.loads(str(yourData))
After that, in your case, the outermost key is "output", and it is another dict, so just use json_data['output'] to access the content inside.
For other keys inside of the "output", like "generic", you can see it is an array with the [] brackets. use json_data['output'][index] first to get the content inside, then use the same method you access a dict to access the content inside of keys like this.
They key here is that the Traceback error indicates an issue with indexing a "List"
This is because a "List" type is a valid JSON type, and generic contains a list of length 1, with a dict inside!
>>> payload['output']['generic']['text']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> type(payload['output']['generic'])
<class 'list'>
>>> len(payload['output']['generic'])
1
>>> payload['output']['generic'][0]
{'response_type': 'text', 'text': 'hi'}
>>> type(payload['output']['generic'][0])
<class 'dict'>
>>> payload['output']['generic'][0]['text']
'hi'
>>>
So, given your expected input JSON format, you will need to know how to index in to pull each required data point.
There are a few packages, glom is one, that will help you deal with missing values from API generated JSON.
I have two json objects represented as a dictionary and I want to concatenate both into one and the last will be a json.
At the moment I have:
obj1 = {
"FS":11440000,
"BW":76000000,
"Gain":62,
"Fc":70000000,
"real":[ 4,2,3,],
"imag":[1,1,3,],
}
obj2 = {
"FS":61440000,
"BW":56000000,
"Gain":62,
"Fc":80000000,
"real":[ 1,2,3,],
"imag":[1,2,3,],
}
I want to have:
[
{
[
{
"FS":61440000,
"BW":56000000,
"Gain":62,
"Fc":70000000,
"real":[ 1,2,3,],
"imag":[1,2,3,],
},
{
"FS":61440000,
"BW":56000000,
"N":8192,
"Gain":62,
"Fc":80000000,
"real":[ 1,2,3,],
"imag":[1,2,3,],
}
],
"ts":1231234165234,
"scale":[10000,-45],
"N":8192,
},
]
How to join obj1 + obj2 and remain the keys and not update them? I need all of them as you can see the final output I'm trying to create.
After concatenating obj1 and obj2 into one I need to add 3 more keys.
I'm using python 3.6.
The dict output you expect is badly formatted, so you will never be able to make it. (dicts needs key for each value - even if value can be list).
foo = {"foo": "value"}
bar = {"bar": "value"}
data = {"ts": "...", "scale": [10000, -45], "N": 8192, "data": [foo, bar]}
Would gives you a dict where you can access data via data['data']
I have a text file which looks like:
{
"content":
[
{
"id": "myid1",
"path": "/x/y"
},
{
"id": "myid2",
"path": "/a/b"
}
]
}
Is there a way to get the value corresponding to "id" when I pass the
"path" value to my method? For example when I pass /a/b I should get "myid2" in
return. Should I create a dictionary?
Maybe explain briefly what it is you need to actually do as I get a hunch that there might be an easier way to do what you're trying to do.
If i understand the question correctly, if you wanted to find the id by passing a value such as "/x/y" then why not structure the dictionary as
{
"content":
{
"/x/y": "myid1"
},
...(more of the same)
}
This would give you direct access to the value you want as otherwise you need to iterate through arrays.
This looks very much like JSON, so you can use the json module to parse the file. Then, just iterate the dictionaries in the "contents" list and get the one with the matching "path".
import json
with open("data.json") as f:
data = json.load(f)
print(data)
path = "/a/b"
for d in data["content"]:
if d["path"] == path:
print(d["id"])
Output:
{'content': [{'path': '/x/y', 'id': 'myid1'}, {'path': '/a/b', 'id': 'myid2'}]}
myid2
I have a json that looks like this:
[
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
I am trying to iterate through the elements array:
for a in json['elements']:
print a['name']
I get this error:
TypeError: list indices must be integers, not str
My python is really bad. Thank you
Try this:
for a in json:
for b in a['elements']:
print b['name']
With your code, you are trying to get the value of the key 'elements' from the dictionary json. But json isn't a dict, but an array of dicts. Thus, what you should do instead is:
for dic_x in json:
for dic_y in dic_x['elements']:
print dic_y['name']
You need to loop through your list and then proceed with your data like what you do with dicts like this example:
my_json = [
{
"status":"passed",
"elements":[{"name":"foo"},{"name":"bar"}]
},
{
"status":"failed",
"elements":[{"name":"foo1"},{"name":"bar1"}]
}
]
for element in my_json:
for v in element["elements"]:
print(v["name"])
Output:
foo
bar
foo1
bar1