Transforming numerous key-value pairs into JSON formatting: utilizing sed in conjunction with an awk for loop

I am currently working with a data file that has 8 columns delimited by pipes. The last column contains an unpredictable number of key-value pairs, each separated by the equals sign and spaces between each pair. However, the challenge is that the values within each pair can also include spaces.

For instance, here is a sample record from the input data file:

Val1|Val2|Val3|Val4|Val5|Val6|Val7| key1=70 key2=11\=12 key3=Some other value key4=Another value

The desired final output should present all key-value pairs in the 8th column in JSON format like this:

Val1|Val2|Val3|Val4|Val5|Val6|Val7|{"key1":"70", "key2":"11\=12", "key3":"Some other value", "key4":"Another value"}

This is a snippet of the current data format I have been able to achieve (assume this is stored in a variable named mydata):

Val1|Val2|Val3|Val4|Val5|Val6|Val7|{"key1":"70 key2":"11\=12 key3":"Some other value key4":"Another value"}

However, what is missing are the necessary ", " characters that would properly separate the previous value from the next key name.

Currently, I need to perform a search and replace operation within the loop of an awk command so that during each iteration, it correctly formats the key-value pairs as specified.

I have formulated the final awk command outline, but it lacks the crucial search and replace operation required for each iteration within the loop:

echo $mydata | awk -F '\":\"' '{ str1 = $1; for (i = 2; i <= NF; i++) str1 = str1 "\":\"" $i; print str1 }'

Thus, the question remains: how exactly do I integrate the necessary search and replace logic into the for loop of the awk command?

An additional piece of code that I have executed up to this point is as follows:

test="Val1|Val2|Val3|Val4|Val5|Val6|Val7| key1=70 key2=11\=12 key3=Some other value key4=Another value";

echo $test | awk -F '|' '{print $1 "|" $2 "\x1c" $3 "|" $4 "|" $5 "|" $6 "|" $7 "|" "{\"" $8 "\"}" }' \
| sed -e 's/{\" /{\"/g' -e 's/\\=/\x07/g' -e 's/[[:space:]]*=/\":\"/g' -e 's/\x07/\\=/g' 

Answer №1

If your data follows a regular pattern and does not contain special characters like " key=" within the values, you can achieve everything using sed with ease. Keys should only consist of word characters:

sed 's/| \(\w\w*\)=/|{"\1"="/;
     s/$/"}/;
     s/ \(\w\w*\)=/" "\1"="/g'

The important thing to remember is that the original "keys" will always have the format <space><word>=

Tested and confirmed:

$ sed 's/| \(\w\w*\)=/|{"\1"="/;s/$/"}/;s/ \(\w\w*\)=/" "\1"="/g'
Val1|Val2|Val3|Val4|Val5|Val6|Val7| key1=70 key2=11\=12 key3=Some other value key4=Another value
Val1|Val2|Val3|Val4|Val5|Val6|Val7|{"key1"="70" "key2"="11\=12" "key3"="Some other value" "key4"="Another value"}

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

Difficulty encountered while extracting information from JSON output

I am new to working with JSON. The more I work with it, the more I find myself liking it. Currently, I have an output that resembles the following structure: [ { "product": { "id": "6", "category": "Books", ...

Unpacking a GZip Stream retrieved from an HTTPClient's Response

I'm attempting to establish a connection to an API that returns GZip encoded JSON from a WCF service (WCF service to WCF service). Utilizing the HTTPClient, I've managed to retrieve the JSON object as a string. However, my goal is to store this d ...

Transmitting a plethora of information using jQuery

Here's the code I currently have for sending data: var test={imagename:"apple.jpg",x:"13",y:"33"}; $.ajax({ type: "POST", url: "some.php", data: test, success: function(response){ console.log(response); } }); ...

How to handle top-level field removal in json4s when there is a nested field with a matching name

I need help removing a specific top-level field named "id" within a JSON structure without accidentally deleting all fields with the same name. Here is the code I have been using: scala> import org.json4s._ import org.json4s._ scala> import org.jso ...

Storing JSON objects directly into MongoDB can be easily achieved with Meteor

Currently exploring Meteor and so far, I am enjoying it :-) However, I am facing challenges while attempting to directly store a JSON object into miniMongo - even though I believed that was the intended purpose :-) testVar = {"test":"this is from the ob ...

What is the best way to extract a particular value from a text that consistently appears a few lines below another value?

This is my method for extracting data from a JSON file: import json json_file = json.load(open('Bla_Bla_Bla.json')) master_data = json_file['messages'] for unique_message in master_data: print(unique_message['text']) H ...

Encountered a problem while trying to retrieve JSON data from Cassandra DB using Java and sparkSession

I am currently working on a project that involves reading data from a Cassandra table using Java with sparkSession. The goal is to format the output as JSON. Here is the structure of my database: CREATE TABLE user ( user_id uuid, email ...

InvalidArgument JSON

I encountered an issue while trying to store String[] in a jsonObject, resulting in the following error message: java.lang.IllegalArgumentException: Invalid type of value. Type: [[Ljava.lang.String;] with value: [[Ljava.lang.String;@189db56] at com.ibm. ...

Deciphering the JSON array generated by PHP

When PHP returns a JSON array, the output may look like this: [ { "uid": "1", "username": "mike", "time_created": "2014-12-27 15:30:03", "time_updated": "2014-12-27 15:30:03", "time_expires": "2014-12-27 15:30:03" }, { "uid": ...

Discovering a way to extract all information from a JSON POST request using curl

Exploring the open data project on spogo.co.uk (Sport England) has been quite engaging. For a search example, check out: https://spogo.co.uk/search#all/Football Pitch/near-london/range-5. I've been experimenting with Cygwin and CURL to POST JSON dat ...

Strip the fields from objects prior to transmitting to json

I have a Jira object that interacts with the Jira rest api. Initially, I only had one Jira project, so dealing with a single set of fields worked perfectly fine. However, as my projects expanded and diversified, each with unique sets of fields, I found mys ...

Working with Swift to safely extract values from a dictionary using guard statements

A JSON call retrieves a dictionary, shown below. It is possible for either of the two values or even the entire "secondLevel" dictionary to be missing. { "theMain" : { "secondLevel" : { "value1" : "5.3", "value2" : "bbb" } ...

Ways to Read JSON without Using jQuery

Exploring JSON Feed and Autocomplete As I delve into the realm of creating an autocomplete feature that fetches data from a JSON feed, I encounter a setback. Despite successfully parsing the JSON data using json2.js through JSON.parse, I am confronted wit ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...

Steps for integrating MongoDB with the Ani Meteor Theme

Having some trouble connecting my MongoDB with the Ani Meteor Theme. I attempted to create a package.json with the necessary configurations, but it didn't work out as expected: { "galaxy.meteor.com": { "env": { "MONGO_URL": "mongodb ...

Guide on building a FastAPI endpoint that can handle both Form and JSON body in one request

Is it possible to design an endpoint in FastAPI that can handle both (multipart) Form data and JSON body? How can I make the endpoint recognize the type of data it is receiving? ...

Error: Unable to extract 'blog' property from 'param' because it is not defined in the Strapi NextJS context

I'm currently developing a blog using NextJS and Strapi. While implementing the comment functionality for my blog posts, I encountered two strange errors: TypeError: Cannot destructure property 'blog' of 'param' as it is undefined. ...

Discovering how to retrieve data from the payload() function when receiving information from Firestore using an Arduino

Utilizing Arduino to access data from Firestore, a database, has been successful. By using the REST API, I managed to retrieve the payload from Firestore. However, my goal now is to store some of this data into a boolean variable. Here is the information ...

Changing Json date format to a Java date object

In my JSON response, there is a CreatedOn Date: { "CreatedOn" : "\/Date(1406192939581)\/" } I am looking to convert the CreatedOn date to a simple date format and then calculate the difference in days between the CreatedOn Date and the Present ...

Best practice for translating a JSON file with extraneous data into a Java object

My Java application receives a large JSON string with nested data from a REST API response. I am using Jackson to map this JSON string to an object, but I only need about 50% of the information provided. How should I model the class that the JSON string wi ...