Adding JSON Objects in Python

In Python 3.8, I have successfully loaded two JSON files and now need to merge them based on a specific condition.

Obj1 = [{'account': '223', 'colr': '#555555', 'hash': True},
        {'account': '134', 'colr': '#666666', 'hash': True},
        {'account': '252', 'colr': '#777777', 'hash': True}]

Obj2 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252'},
        {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569'},
        {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387'}]

# Desired Merged Result

Obj3 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252', 'account': '252', 'colr': '#777777', 'hash': True},
        {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569', 'account': '223', 'colr': '#555555', 'hash': True},
        {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387', 'account': '134', 'colr': '#666666', 'hash': True}]

I have attempted various methods such as append and extend from resources like Stack Overflow but still face difficulties with the specific condition.

The objective is to add elements from Obj1 into Obj2 at their appropriate positions based on the condition where if the colr value of an element in Obj1 matches part of the desc value in Obj2, then that entire element from Obj1 should be appended to the corresponding element in Obj2. Alternatively, creating a new Obj3 for displaying the updated values.

References consulted include: Append JSON Object, Append json objects to nested list, Appending json object to existing json object among others without success.

Hopefully, this clarifies the situation. Thank you.

Answer №1

This basic solution should suffice.

for x in range(len(array1)):
    for y in range(len(array2)):
        if array1[x]['color'] in array2[y]['description']:
            array1[x].update(array2[y])

print(array1)

Answer №2

To start, one way is to initially establish a dictionary that links each color to the corresponding JSON element. This can be achieved by:

color_to_element = {element['color']: element for element in json_data1}

Afterwards, you can determine which color needs to be added by using a Regular Expression on the description and then update the json_data2 dictionary by combining the dictionaries.

import re

for element2 in json_data2:
    element1 = color_to_element.get(re.search('#\d+', element2['description']).group(0))
    element2.update(element1 if element1 is not None else {})

Answer №3

Element1 = [{'account': '223', 'colr': '#555555', 'hash': True},
             {'account': '134', 'colr': '#666666', 'hash': True},
             {'account': '252', 'colr': '#777777', 'hash': True}]

Element2 = [{'sn': 38796, 'code': 'df', 'id': 199, 'desc': 'jex - #777777- gg2349.252'},
             {'sn': 21949, 'code': 'se', 'id': 193, 'desc': 'jex - #555555 - gf23569'},
             {'sn': 21340, 'code': 'se', 'id': 3, 'desc': 'jex - #666666 - gf635387'}]

Element3 = []
for x in Element1:
    for y in Element2:
        if x["colr"] == y["desc"][6:13]:
            z = {**y, **x}
            Element3.append(z)
print(Element3)

Answer №4

If you want to compare elements in two arrays, you can use the code

element1['colr'] in element2['desc']
. This will help you determine if there are any matches between the elements. To further process these matching elements, iterate over the second array and find their corresponding element in the first array using the following condition:

json_obj3 = []
for element2 in json_obj2:
    for element1 in json_obj1:
        if element1['colr'] in element2['desc']:
            element3 = dict(**element1, **element2)
            json_obj3.append(element3)
            break  # stop inner for loop, as the matched element is found

Alternatively, you can condense this process into a single expression by utilizing nested list comprehensions:

json_obj3 = [
    dict(**element1, **element2)
    for element1 in json_obj1
    for element2 in json_obj2
    if element1['colr'] in element2['desc']
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...

Python Selenium - Trouble clicking button element without redirecting to desired link

I am currently conducting a test on a web user interface using Selenium in Python. In one of the test cases, there is a button that should redirect to another page when clicked. However, despite executing the code without any errors, the page does not red ...

Error: The object with the memory address 0x7f3f4bd01470 returned by the neo4j.work.result.Result is not compatible with JSON serialization

Hello, I am facing an error with the following code and need assistance in resolving it: class GenerateQuery: @staticmethod def get_nlg(graph_query): # graph = Graph("http://localhost:7474",auth=("neo4j", "pass" ...

Retrieve JSON elements from a MYSQL database where the JSON data is present

In my database, I have a table orders which contains orders.items in JSON format. An example of the orders.items cell looks like this: { "10": { "name": "item 1", "step": "1", "price": "140", "amount": "4", ...

Simultaneously managing both stepper motors and a camera

What is the optimal method for simultaneously controlling a stepper motor and camera? Imagine having a camera mounted on a linear stage driven by a stepper motor, with the goal of moving the stage in 1mm increments while capturing an image at the end of e ...

"Need assistance with npm ERR! Can anyone provide some help,

Recently, I created a notepad file in my directory called "package.json". Inside this file, I typed the following: { “name”: “Bot”, “version”: “1.0.0”, “description”: “My First Discord bot”, “main”: “bot.js”, “author”: ...

Python code for comparing two sets of data, determining the best match, and calculating the percentage of the match

I’ve been searching high and low for answers on this topic, but I haven't found anything that quite fits the bill. Any advice or insights you could offer would be greatly appreciated! My dilemma involves dealing with 2 lists, each of which consist ...

A guide on retrieving nested objects from my API and parsing the resulting data in each iteration for individual elements

Struggling to update my website with a new API, specifically with accessing nested objects in a loop. Still trying to wrap my head around ajax and JSON concepts. Take a look at the API output and JS code I've been working on for a better understanding ...

What is the process for converting a video feed to fullscreen using OpenCV?

When attempting to apply Canny edge detection, I noticed that the borders of the video are also being detected. How can I remove these borders? I am using the built-in webcam to capture the video and have observed that the original frame contains borders a ...

Flexible Array Properties within Custom Object

Trying to construct a unique object from server feedback that contains constant fields plus an object array is my current task. I'll refer to it as a DynamicResponse. Each instance of DynamicResponse will have the same kind of custom objects in its ar ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Troubles encountered when trying to save an Excel.Writer document to a different directory

A timed backup system is being developed for an Excel document using Python, since there will be multiple users accessing it. The goal is to alter the file path away from the local directory. Below is the code snippet; import pandas as pd import datetime ...

Tips for utilizing the ng-filter Json [@attributes] with Angularjs

I'm trying to sort through sports feed based on sport ID, but the JSON feeds are structured with @attributes. JSON Feeds series: [ { @attributes: { id: "cdf590b4-0206-45b0-9122-20eae46a2b27", name: "Pakistan tour of Sri Lanka, 2015", year ...

Discovering an element within the identical class as another element using Selenium in Python

If I have already located an element, is there a method to find another in the same category? For instance: <div class="day"> <span class="day_number">4</span> <span class="day_item_time" data-day-total-time="day-total-time">1 ...

Navigating through JSON arrays with Node.js

I have been given the task of iterating through a complex JSON file that contains an array of JSON objects. I am finding it difficult to access the array object within the JSON file. Specifically, I need to access the "class-name" object from the JSON f ...

I am unable to display images in my Full screen Activity when I receive them from my JSON response, even when swiping

How can I implement swipe functionality for full screen images within a GridView while loading the images from a JSON response? I am new to Android and seeking guidance from my friends. I want to achieve this using only one JSON URL in my program, where I ...

How come Python 2.7 is getting 3 x 2 as 33? I must be making a mistake somewhere

I am new to learning and currently facing an issue when trying to define the variable b- def b(): b() b = a * 2 print "If you double it..." time.sleep(3) print "..you have",b -When I input 3 for b, I am getting 33 as the answer for multiplication. C ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

List style image does not serve its intended purpose

I attempted to personalize my webpage by adding an image to a list, but I couldn't get the list-style image to work. You can view the page at Below is the code I used: CSS /* Fleet List */ ul#flotta li { list-style-image:url("http://ctp.serviziew ...

An error has arisen: ImportError unable to bring in the name 'imap' from 'itertools' (location unknown)

System Information: Operating System: Linux Mint 20 Ulyana Kernel Version: 5.4.0-65-generic Architecture: 64-bit Compiler: gcc v9.3.0 Desktop Environment: Cinnamon 4.6.7 Window Manager: muffin Display Manager: LightDM Distro Base: Ubuntu 20.04 focal I tho ...