sed is not able to pick out the values

Looking for assistance with the sed command. I am trying to extract JSON values and assign them to variables using sed. Can someone provide guidance on how this can be achieved?

For example:

echo "{url:news.google.com,int:3}" | sed ?
url=news.google.com
int=3

Answer №1

Here is a suggestion for using the sed command to extract specific information:

url=$(echo "{website:example.com,int:5}" | sed 's/\({\)\([^:]*\)\(:\)\([^,]*\)\(.*\)/\4/')
echo "$url"
example.com

int=$(echo "{website:example.com,int:5}" | sed 's/.*://;s/}//')
echo "$int"
5

Answer №2

It is recommended to use sed only for handling simple JSON structures that you have full control over. For nested or more complex JSONs, jq, Perl, Python and similar tools are a better choice, as mentioned by Sundeep.

Having said that,

echo "{url:news.google.com,int:3}" | sed 's/{//;s/}//;s/:/=/g;s/,/\n/g'

This command will generate the desired output.

Answer №3

Instead of using a specialized JSON parser, you can utilize grep to extract specific data from the given information.

grep -oP 'url:\K[^,}]*' 

Here are the test results:

$ echo "{url:news.google.com,int:3}" | grep -oP 'url:\K[^,}]*' 
news.google.com

$ echo "{url:news.google.com,int:3}" | grep -oP 'int:\K[^,}]*' 
3
  • The use of \K resets the previously matched data

To store the extracted value in a variable, you can wrap the command inside $(...) like this:

url=$( echo "{url:news.google.com,int:3}" | grep -oP 'url:\K[^,}]*' )

Alternatively:

$ url=$( grep -oP 'url:\K[^,}]*' <<<"{url:news.google.com,int:3}" )
$ echo $url
news.google.com

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

Converting a JSON string into a JSON array

Hey there! I'm currently working with an array of JSON objects that looks like this: [{ "senderDeviceId":0, "recipientDeviceId":0, "gmtTimestamp":0, "type":0 }, { "senderDeviceId":0, "recipientDeviceId":0, "gmtTimestamp":0, " ...

Arrange a JSON file by organizing a key located within an array of dictionaries using Python

Here's a structure that I am working with: [{ "name": "apple", "price": "5.0", "record": [ { "id": "008", "time": 1465689600 } ] },{ "name": "banana", "price": "9.0", "record": [ ...

Creating a multi-level JSON object from a string: A step-by-step guide

I've organized my HTML file in the following structure: Chapter 1.1 1.1.1 interesting paragraph 1.1.1.1 interesting paragraph Chapter 1.2 1.2.1 interesting paragraph 1.2.1.1 interesting paragraph ... Chapter 11.4 ... 11.4.12 interesting ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

"Compilation error: 'not defined' is not recognized, 'no-undef

I am currently working on a login form that will fetch values from this API: However, the password field is currently empty, allowing any password to be accepted. This results in the error: Failed to compile 'userName' is not defined no-undef; ...

Jackson's @JsonAppend annotation with a predefined default value

Hey all! I'm currently in the process of building a web application and have chosen Jackson as my JSON processing framework. In terms of the request data I want to send, imagine my POJO structure like this: data class JSONEnvelope( @JsonProp ...

Troubleshooting ASP.NET MVC and Ajax json Datatables: encountering errors with json and cells not displaying proper data

I have exhausted all resources on stack exchange and datatables.net forums trying to solve this issue, but I still can't get it to work. My problem lies with the var listOfFiles, which is a list of the model shown below (List<AudioModel>): pub ...

Requesting data from server using Ajax with multiple JSON responses

I'm facing a situation where my Ajax script calls a PHP file to make a query to MySQL and then formats the response in JSON. The challenge is that I need to retrieve data from different tables based on the id sent with the Ajax call. Some tables retur ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

Trouble with Swagger UI 2.1: Unable to retrieve resource list

Lately, I have been working on a RESTful API that I recently created. However, knowing myself, I'll probably forget how to use it in a few months. To avoid this, I decided to document my API using Swagger, but little did I know the frustrations that w ...

It appears that the npm installation is incorrect

When attempting to install the npm in an Alpine Linux container, a series of errors occurred during the process. The errors included warnings about preferring global installations, failures with post-install commands, and issues with pre-build tests. $ np ...

Removing class metadata for Neo4j in Json format: A step-by-step guide

I currently have this code snippet in my ASP.Net Web Api project. The resulting data is then sent back to the client. var query = graphClient.Cypher .Start(new { user = userNode.Reference, cultureInfo = startNode.Reference }) ...

Guide on utilizing PHP to display a particular value from a JSON file

Hello, I am trying to extract specific data from a JSON response. Here is the structure of the JSON: { "data":{ "user_quota":[ { "group_limit":10240, "quota":0, "support_share_quota":false, ...

Retrieve data from MySQL using a count query and convert the results into a JSON format

In my table, there is a column with datetimes and corresponding IDs. +----+---------------------+ | id | datetime | +----+---------------------+ | 0 | 2016-09-02 12:13:13 | | 1 | 2016-09-02 10:16:11 | | 2 | 2016-09-05 11:03:23 | | 3 | 2016- ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...

Using PHP, send the keys and values of an array to a CSV file

My goal is to have all the keys of an array appear in the first column (Column 0) of an Excel spreadsheet, with the corresponding values populating the rest of the columns in the CSV file (Columns 1-5). Check out the examples below Here is the code I am ...

Is there a way to retrieve a specific string from a PHP response containing multiple objects?

I have a $response variable that retrieves data from a Square API call. By using var_dump($response), the following output is produced: object(Square\Http\ApiResponse)#26 (8) { ["request":"Square\Http\ApiResponse": ...

Problem with parsing JSON in a mixed array

When making a YouTube API call, the response includes a var result = JSON.stringify(response, '', 2); that has the following structure: { "kind": "youtube#searchListResponse", "pageInfo": { "totalResults": 1000000, ...

Discovering a Match within a JavaScript Object and Array with the help of Jquery's Each

I am currently working on implementing an array of filters to search through a JavaScript object containing store locations. My goal is to find a full match using both filters from the filters array, which currently has 2 items but will eventually have mor ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...