Create an json object in Python - python

I need to create a json string like in the example below and I am thinking of using a dict that I can ultimately json.dumps to a json string. I will build this dict in a loop. This is what the json should look like
{
"big-data-list" :[
{
"indexnum": "1",
"components" :
[
{
"key": "some-key1",
"item" :"item name",
"data" :"some string",
}
]
},
{
"indexnum": "2",
"components" :
[
{
"key": "some-key2",
"item" :"item name 2",
"data" :"some string 2",
},
{
"key": "some-key3",
"item" :"item name 3",
"data" :"some string 3",
}
]
}
}
Here is what I tried without a loop to see how things work
bigdata= {}
indexnum= {}
componentList = {}
indexnum["components"] = {}
indexnum["mileage"] = 20
componentList["key"] = "some-key1"
componentList["item"] = "item name"
componentList["data"] = "some string"
indexnum["components"][0] = componentList
componentList["key"] = "some-key2"
componentList["item"] = "item name 2"
componentList["data"] = "some string 2"
indexnum["components"][1] = componentList
print(json.dumps(indexnum))
What I end up getting looks like this:
{"components": {"0": {"key": "somekey2", "item": "fuel2"}, "1": {"key": "somekey2", "item": "fuel2"}}, "mileage": 20}
How do I build the dict so I can json dump it in the way I need to? Is there a better way to come up with such a json object as represented in the example above?

You basically just need to work on your logic to put your data in the appropriate structure of dicts and lists.
Below is an example of a loop that puts some data into the specified structure:
>>> # say you originally have your data in the following list
... lists_of_components = [
... [("some-key1", "item name", "some string")],
... [("some-key2", "item name 2", "some string 2"),
... ("some-key3", "item name 3", "some string 3")],
... ]
... bigdata = {}
... bigdata["big-data-list"] = []
... for i, components in enumerate(lists_of_components, 1):
... bigdata["big-data-list"].append({
... "indexnum": str(i),
... "components": [
... {k: v for k, v in zip(["key", "item", "data"], component)}
... for component in components]
... })
... print(json.dumps(bigdata, indent=4))
{
"big-data-list": [
{
"indexnum": "1",
"components": [
{
"key": "some-key1",
"item": "item name",
"data": "some string"
}
]
},
{
"indexnum": "2",
"components": [
{
"key": "some-key2",
"item": "item name 2",
"data": "some string 2"
},
{
"key": "some-key3",
"item": "item name 3",
"data": "some string 3"
}
]
}
]
}

Related

Creating a custom json from existing json

I have Json something like below
Input Json
"blocks": [
{
"key": "",
"text": "Contents",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [
{
"offset": 0,
"length": 8,
"style": "BOLD"
}
],
"entityRanges": [],
"data": {}
},
{
"key": "",
"text": "1.\u00a0\u00a0\u00a0\u00a0 Completed\n Activities & Accomplishments\u00a0 1",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [
{
"offset": 0,
"length": 49,
"key": 0
}
],
"data": {}
},
{
"key": "",
"text": "2.\u00a0\u00a0\u00a0\u00a0 Planned Activities for\n Next Reporting Period\u00a0 3",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [],
"entityRanges": [
{
"offset": 0,
"length": 55,
"key": 1
}
],
"data": {}
},
I am trying to extract "text" key data and want to convert it into new json in the key value format
I am able to extract text properly now I just wanna know how to separate numeric from letters successfully
def jsontojson():
with open('C:\Extraction\Docs\TMS TO 692M15-22-F-00073 Monthly Status _ Financial Report July 2022.json') as json_file:
# json1=json_file.read()
json1=json.load(json_file)
value=""
for dict1 in json1["blocks"]:
# print(dict1)
for key in dict1:
if key=="text":
value+=dict1[key]
dict2={}
d=value.split()
print("Value of d",d)
if str(d).isdigit():
dict2['key1']=d
else:
dict2['desciption']=d
print("Dictionary is",dict2['key'])
For the above code it gives me Key error : key1
Let me know where i am wrong or what I need to do so that i can get the Output
Expected OUTPUT
[
{
"key": "",
"text": "Contents"
},
{
"key": "1.",
"text": "Completed Activities & Accomplishments"
},
{
"key": "2.",
"text": "Planned Activities for Next Reporting Period"
},
]
Try (json1 contains the data from your question):
import re
out = []
for d in json1["blocks"]:
num = re.search(r"^(\d+\.)\s*(.*)", d["text"].replace("\n", ""))
out.append(
{
"key": num.group(1) if num else "",
"text": (num.group(2) if num else d["text"]).rsplit(maxsplit=1)[0],
}
)
print(out)
Prints:
[
{"key": "", "text": "Contents"},
{"key": "1.", "text": "Completed Activities & Accomplishments"},
{"key": "2.", "text": "Planned Activities for Next Reporting Period"},
]
Another and easy way is (if your first list is called "Mylist" :
new_list =[]
for dic in Mylist:
new_list.append({'key':dic['key'],
'text':dic['text']})

Formatting issue, when python dictionary is dumped in to json objects

I have two dictionaries - test1 and test2. I have to recursively compare both, if test1 contains key description$$, I have to replace second test2 of same key with the value of test1 key and then dump this in to a JSON file. I was able to get this, but the output of JSON file is not as of expected format.
sample.py
import json
test1 = {
"info" : {
"title" : "some random data",
"description$$" : "CHANGED::::",
"version" : "x.x.1"
},
"schemes" : [ "https" ],
"basePath" : "/sch/f1"
}
test2 = {
"info" : {
"title" : "some random data",
"description" : "before change",
"version" : "x.x.4"
},
"schemes" : [ "https" ],
"basePath" : "/sch/f2"
}
def walk(test1, test2):
for key, item in test1.items():
if type(item) is dict:
walk(item, test2[key])
else:
if str(key) == "description$$" or str(key) == "summary$$":
modfied_key = str(key)[:-2]
test2[modfied_key] = test1[key]
walk(test1, test2)
json.dump(test2, open('outputFile.json', "w"), indent=2)
My output is -
outpufile.json
{
"info": {
"title": "some random data",
"description": "CHANGED::::",
"version": "x.x.4"
},
"schemes": [
"https"
],
"basePath": "/sch/f2"
}
but the expected output should be -
{
"info": {
"title": "some random data",
"description": "CHANGED::::",
"version": "x.x.4"
},
"schemes": ["https"],
"basePath": "/sch/f2"
}
the schema should be printed in single line, but in my output it's taking 3 lines. how can I fix this?
Thank you

Find a value in a list of dictionaries

I have the following list:
{
"id":1,
"name":"John",
"status":2,
"custom_attributes":[
{
"attribute_code":"address",
"value":"st"
},
{
"attribute_code":"city",
"value":"st"
},
{
"attribute_code":"job",
"value":"test"
}]
}
I need to get the value from the attribute_code that is equal city
I've tried this code:
if list["custom_attributes"]["attribute_code"] == "city" in list:
var = list["value"]
But this gives me the following error:
TypeError: list indices must be integers or slices, not str
What i'm doing wrong here? I've read this solution and this solution but din't understood how to access each value.
Another solution, using next():
dct = {
"id": 1,
"name": "John",
"status": 2,
"custom_attributes": [
{"attribute_code": "address", "value": "st"},
{"attribute_code": "city", "value": "st"},
{"attribute_code": "job", "value": "test"},
],
}
val = next(d["value"] for d in dct["custom_attributes"] if d["attribute_code"] == "city")
print(val)
Prints:
st
Your data is a dict not a list.
You need to scan the attributes according the criteria you mentioned.
See below:
data = {
"id": 1,
"name": "John",
"status": 2,
"custom_attributes": [
{
"attribute_code": "address",
"value": "st"
},
{
"attribute_code": "city",
"value": "st"
},
{
"attribute_code": "job",
"value": "test"
}]
}
for attr in data['custom_attributes']:
if attr['attribute_code'] == 'city':
print(attr['value'])
break
output
st

Get Value of a key from List of dictionary

I have a list of dictionaries with 2 keys: 'name' & 'value'. I need to get the value of 'value' key if value of 'name' key is 'Subject'
Currently i'm iterating through each dict and checking the value of 'name' and getting the value of 'value'. Is there any improved way of doing this ?
items = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "To",
"value": "sender#example.com"
},
]
for item in items:
if item.get('name') == 'Subject':
print "Subject: " + item.get('value')
You should transpose your data into a dict instead:
>>> d = dict([(e['name'],e['value']) for e in items]) # transpose
Or a slightly easier way as mentioned by Peter Wood in the comments:
>>> d = {e['name']: e['value'] for e in items}
Then just use the dict as normal:
>>> d['Subject']
'Test Subject'
You could use next along with a generator filtering and converting the items.
>>> subject = next(field['value']
... for field in items
... if field['name'] == 'Subject')
As Jonas told, better for modify your structure because
from collections import defaultdict
it = [
{
"name": "From",
"value": "from#example.com"
},
{
"name": "Date",
"value": "Tue, 8 Sep 2014 16:18:35 +0530"
},
{
"name": "Subject",
"value": "Test Subject"
},
{
"name": "Subject",
"value": "Test Subject 55"
},
{
"name": "To",
"value": "sender#example.com"
},
]
result = defaultdict(list)
# shorcut better to use for...
[result[item["name"]].append(item["value"]) for item in it]
print(result["Subject"])
['Test Subject', 'Test Subject 55']

how to filter json array in python

That is the current json array I have.
I want get all json objects that type=1
before filter:
[
{
"type": 1
"name" : "name 1",
},
{
"type": 2
"name" : "name 2",
},
{
"type": 1
"name" : "name 3"
},
]
after filter:
[
{
"type": 1
"name" : "name 1",
},
{
"type": 1
"name" : "name 3"
},
]
please help.
The following snippet of code does exactly what you want, but BEWARE that your input (as written in the question) is not a valid json string, you can check here: http://jsonlint.com.
import json
input_json = """
[
{
"type": "1",
"name": "name 1"
},
{
"type": "2",
"name": "name 2"
},
{
"type": "1",
"name": "name 3"
}
]"""
# Transform json input to python objects
input_dict = json.loads(input_json)
# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if x['type'] == '1']
# Transform python object back into json
output_json = json.dumps(output_dict)
# Show json
print output_json
Simply
print [obj for obj in dict if(obj['type'] == 1)]
Example Link.
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Documentation for filter
>>> obj=[
... {
... "type": 1,
... "name": "name 1"
... },
... {
... "type": 2,
... "name": "name 2"
... },
... {
... "type": 1,
... "name": "name 3"
... }
... ]
>>> filter(lambda x: x['type'] == 1, obj)
<filter object at 0x7fd98805ca00>
>>> list(filter(lambda x: x['type'] == 1, obj))
[{'type': 1, 'name': 'name 1'}, {'type': 1, 'name': 'name 3'}]
>>> list(filter(lambda x: x['type'] == 2, obj))
[{'type': 2, 'name': 'name 2'}]

Categories