0

I get this response from a remote server.

A has 100 products\n   Brought: \n      ID/234 has brought 8 products\n      ID/212 has brought 72 products\n   Not Brought\n\n B has 0 products\n   Brought\n   Not Brought\n

When I execute my node js script on the terminal this response is displayed as a table as shown in the screenshot below.

enter image description here

I want this output as JSON.

Here is my code.

function(err, res) {
        product=res.content; //store the response in variable
        var prodArr = [];
        var obj = product.split('\n'); //split the response at new lines
    for(var i= 1; i<obj.length; i=i+1)
    {
                prodArr.push({
                    data : obj[i]
                 });

            }
        console.log(prodArr);
    })
}

And here the JSON I get when I execute the above script.

{ data:'A has 100 products' },
{ data: 'Brought: '},
{ data:'ID/234 has brought 8 products ' },
{ data:'ID/212 has brought 72 products ' },
{ data: 'Not Brought' },
{ data:'B has 0 products' },
{ data: 'Brought: '},
{ data: 'Not Brought '},

But I want JSON which should be something like this as shown below :

{
"data":{
  "title": "A has 100 products",
"Brought": {
"1" : "ID/234 has brought 8 products",
"2" : "ID/212 has brought 72 products"
},
"Not Brought" : {
    }
 }
},

{
"data":{
  "title": "B has 0 products",
"Brought": {
},
"Not Brought" : {
    }
 }
}

How do I do that?

3
  • 3
    Hi! Please read through the help center, in particular How do I ask a good question? The code you've shown doesn't do anything to create the output you've said you want. Build up the object structure in memory, then use JSON.stringify to create the JSON for it. Your best bet here is to do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Commented Aug 28, 2018 at 9:51
  • When you clicked to create this post the button said "Ask Question". But "I want" or "I need" is not a question. "How do I" is generally too broad and vague, unless it's something very very simple. We will help you fix bugs, not just do your work for you completely. What research have you done? What code have you tried? What problem are you facing? Please read stackoverflow.com/help/how-to-ask for further guidance on how to ask a useful question. Commented Aug 28, 2018 at 10:05
  • Basically though you need to start checking the content of each line before you blindly add it to the array, and using that to decide what step you're at in building your object, and then act accordingly. Try writing yourself some simple rules for how you (as a human) would manually process the data into the structure you want - write it as if you're describing it to someone you'll never speak to in person (i.e. thoroughly and without ambiguities, so they don't have to ask you). That gives you your requirements and process. After that, try to turn that into JavaScript code. Commented Aug 28, 2018 at 10:06

2 Answers 2

1

You need to use regex to figure out the position of title elements and the brought and not brought items as the solution is completely specific.

var input = "A has 100 products\n   Brought: \n      ID/234 has brought 8 products\n      ID/212 has brought 72 products\n   Not Brought\n\n B has 0 products\n   Brought\n   Not Brought\n";
var splitInput = input.split('\n'); // split with newline
var formattedInput = splitInput.map(slice => slice.trim()); // trim extra spaces
var titleIndices = [], broughtIndices = [], notBroughtIndices = []; // figure out necessary indices in string
for(var i = 0; i < formattedInput.length; i++) {
 if(/\w+ has \d+ products/.test(formattedInput[i])){
    titleIndices.push(i);
  }
 if(/^Brought\:?/.test(formattedInput[i])) {
  broughtIndices.push(i);
 }
 if(/^Not Brought\:?/.test(formattedInput[i])) {
  notBroughtIndices.push(i);
 }
}
const output = [];
for(var i = 0; i < titleIndices.length; i++) {
  const broughtLength = notBroughtIndices[i] - broughtIndices[i] - 1;
  let brought = {};
  for(var j=0; j < broughtLength; j++) {
    const broughtItem = formattedInput[broughtIndices[i]+1+j];
    if(broughtItem) {
     brought[j+1] = broughtItem;
    }
  }
  const notBroughtLength = (titleIndices[i+1] || notBroughtIndices[i] ) - notBroughtIndices[i] - 1;
  let notBrought = {};
  for(var j=0; j < notBroughtLength; j++) {
    const notBroughtItem = formattedInput[notBroughtIndices[i]+1+j]
    if (notBroughtItem) {
    notBrought[j+1] = notBroughtItem;
  }
  }
 output.push({
  data: {
    title: formattedInput[titleIndices[i]],
    Brought: brought,
    "Not Brought": notBrought,
  }
 });
}
console.log(JSON.stringify(output))

Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot. I used the logic from your code and it worked for me
can you help me with this
1

var InputValue=['A has 100 Product','Brought','ID/1251 brought 8 Product','ID/1252 brought 4 Product','Not Brought','B has 100 Product','Brougth','ID/1222 brought 8 Product','ID/1333 brought 2 Product','Not Brought']
var prodArr={};
var finalResult=[];
var BroughtArr=[]
let i=0;
for(i=0;i<InputValue.length;i++){
    if(i==0){
         prodArr['Title']=InputValue[0];
         i++;
    }
    if(InputValue[i]==='Brought'){
       ++i;
       for(let j=i;j<InputValue.length;j++){
          if(InputValue[j]!='Not Brought'){
           BroughtArr.push(InputValue[j]);
         }else{
           prodArr['Brought']=BroughtArr
           finalResult.push(prodArr);
           BroughtArr=[]
           prodArr={}
           if(i<InputValue.length)
           prodArr['Title']=InputValue[++j];
           i=++j;
         } 
       }
     }
}
console.log(finalResult)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.