Searching for specific information within a JSON file (across multiple lines)

Currently, I am working on extracting specific lines of data from a JSON file. It seems that using grep in this particular scenario might be the way to go, but I could use some guidance. Below is an example of the JSON data:

 [ 'vlans VLAN10 vlan-id 10',
 'vlans VLAN100 vlan-id 100',
 'vlans VLAN20 vlan-id 20',
 'vlans VLAN30 vlan-id 30',
 'vlans default vlan-id 1',
 'vlans vlan111 vlan-id 111',
 'vlans vlan222 vlan-id 222',]

This is what I have tried so far:

config_json = results.json()
config_json_dumps = json.dumps(config_json)
pattern = 'vlan-id'
for vlans in config_json_dumps:
    if re.search(pattern, vlans):
        print(pattern)

Unfortunately, my attempt only returns a blank response with code 0.

Answer №1

When using request.json(), you will receive a list of strings without needing to convert them into string format. To determine if a line contains the term vlan-id, there is no requirement for using regex.

config_json = [
 'vlans VLAN10 vlan-id 10',
 'vlans VLAN100 vlan-id 100',
 'vlans VLAN20 vlan-id 20',
 'vlans VLAN30 vlan-id 30',
 'vlans default vlan-id 1',
 'vlans vlan111 vlan-id 111',
 'vlans vlan222 vlan-id 222',
]

pattern = 'vlan-id'

for line in config_json:
    if pattern in line:
        print(line)

In your given example, all lines contain 'vlan-id', hence checking for this may seem unnecessary.

However, if your objective is to extract the number following 'vlan-id', it would be pertinent - necessitating the use of regex.

config_json = [
 'vlans VLAN10 vlan-id 10',
 'vlans VLAN100 vlan-id 100',
 'vlans VLAN20 vlan-id 20',
 'vlans VLAN30 vlan-id 30',
 'vlans default vlan-id 1',
 'vlans vlan111 vlan-id 111',
 'vlans vlan222 vlan-id 222',
]
        
import re

for line in config_json:
    result = re.search('vlan-id (\d+)', line)
    if result:
        print(result[1]) 

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

I am looking to convert a list of dictionaries into a list of lists using Python

I am attempting to convert a list of dictionaries into a list of lists in Python. Here is an example of the data: before_data = [ { "itemid": "23743", "lastclock": "1574390042", "lastvalue": "2798", "name": "cl Loaded ...

Typing into a form field using Selenium

I'm having trouble interacting with the payment information input fields. It seems they are nested within iframes, and I cannot switch between frames successfully. Attached is a snapshot of the HTML code and the corresponding webpage. Any assistance i ...

Issue 400: wcf request error received from the client side

I am a beginner to WCF and facing some challenges. I am trying to call a WCF service from my aspx page to post XML data and receive JSON in return. The WCF service seems to be working fine, but I keep getting an error saying "The remote server returned an ...

Converting Json into an object generated by NJsonSchema, complete with enums that include spaces

I am seeking assistance. Recently, I encountered an issue with JSON schema and the NJsonSchema.CodeGeneration tool. I was able to successfully deserialize JSON into objects until I came across enum values with spaces in them. For example: In the schema, ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...

Is it possible for Python to fail to identify the conclusion of a term in an if-else clause?

Looking to create a function that returns true if the first and last characters of a string are the same, otherwise false. This is my current code: def same_first_and_last_letter(str): if s[0] == s[-1]: return True else: return Fa ...

Retrieve the p-value associated with the intercept using scipy's linregress function

The function scipy.stats.linregress outputs a p-value for the slope, but not for the intercept. Here's an example from the documentation: >>> from scipy import stats >>> import numpy as np >>> x = np.random.random(10) >&g ...

Is there a way to transmit the Ctrl key to the terminal using subprocess commands?

Hey there, I'm currently working on a script to automate the process of opening tmux and splitting windows in my terminal. The key combination needed for this operation is sending tmux along with Ctrl + b and %. def create_window(): subprocess.c ...

Issue with function argument types is causing failure of Sphinx autodoc extension for python versions higher than 3.5

Recently, I've been working on setting up autodoc to automatically generate documentation for my Python 3.7 module. The specific file that needs documenting is the init.py file within a single module. This particular file contains functions with docst ...

Analyzing the radial intensity patterns of evenly divided sections within circular formations

Hey there, I'm currently facing a challenge that I could really use some help with. I've been searching for a solution but haven't had much luck so far. As a biologist delving into automated image analysis for my work, I might be in the wron ...

Continue executing without stopping

After making 4 ajax calls, the script is supposed to halt if record number 123456 is found. However, this specific record may appear in all four ajax responses. Despite this expectation, the code fails to stop processing. var endPoint0 = ''; var ...

The DataFrame is grouped together to analyze the count of distinct values within each group

I've attempted the following code: df.groupby(['Machine','SLOTID'])['COMPONENT_ID'].unique() The resulting output is as follows: Machine COMPONENT_ID LM5 11S02CY382YH1934472901 [N3CP1.CP] 11S02C ...

How can one aggregate all the values in a key/value JSON in Postgres?

Here is my question: select datetime,array_to_json(array_agg(json_build_object('parameter',parameter,'channel_id',channel_id,'value',value,'status',status,'units',units))) as parameters from dbp_istasyonda ...

An efficient method for computing the matrix product A multiplied by its transpose in Python (without using numpy)

If you have a list called A that contains only 0's and 1's in the form of nested lists, what is the most pythonic (and efficient) method to calculate the product of A * A' without relying on numpy or scipy? One way to achieve this using num ...

Why do I keep receiving the unprocessed JSON object instead of the expected partial view output?

Upon submitting my form, instead of displaying the testing alerts I have set up, the page is redirected to a new window where the raw JSON object is shown. My assumption is that this occurrence is related to returning a JSON result from the controller. How ...

Troubleshooting an issue where an ASP.NET jQuery AJAX call to a PageMethod is resulting in a parsererror

It seems like the issue I'm facing is that the PageMethod is not returning JSON. Do I need to make any additional changes on the server side to ensure the return value is properly formatted? Is there a missing step that I am overlooking? (Please note ...

Processing and displaying JSON data along with nested attributes

Here are some of the classes I have: class Product attr_accessible :name, ... has_many :images end class Image attr_accessible :image, :position, :product_id, :title belongs_to :product In this case, I am trying to achieve the following action: def ...

Experiencing an AssertionError: The result must be None, a string, bytes, or StreamResponse. Having trouble finding a resolution to this issue?

I have implemented a post API that reads JSON content from a file. When a request is made to the API, the device_id is provided. Using this device_id, I fetch entities related to it. Here's the code snippet: class EntityBasedOnDeviceId(HomeAssistantVi ...

The Django server fails to display the CSS files upon activation

Despite having all the static files in place, only the plain HTML loads without any styles for some unknown reason. I've attempted using collectstatic and even setting up a new project, but to no avail. STATIC_URL is also properly specified along with ...

What could this error be in Chrome console: "Uncaught SyntaxError: Unexpected token ':'"

Why am I getting this error in the Chrome console: "Uncaught SyntaxError: Unexpected token ':'"? I have a JSON file located at the root of my application: <script src="levels.json"></script> Here is the content of my JSON file: { ...