-6

I have dynamic data coming into my website like this:

[{
  "itemOne": { 
     "url": "www",
     "name": "Bob" 
  },
  "itemTwo": {
     "url": "www",
     "name": "fred"
  }
}]

Using jQuery or Javascript, I would like to turn this data into JSON, so it would be structured like this:

"products": {
    "itemOne": {
       "url": pageUrl,
       "name": productName
    },
    "itemTwo": {
       "url": pageUrl,
       "name": productName,
    }
}

Is this possible? If so, how would I go about it?

2 Answers2

2

To achieve this you can just take the first object from the array and set it as the value of the product property of a new object. If you need to turn this object in to JSON, call JSON.stringify on the result. Try this:

var arr = [{
  "itemOne": {
    "url": "www",
    "name": "Bob"
  },
  "itemTwo": {
    "url": "www",
    "name": "fred"
  }
}]

var obj = {
  products: arr[0]
}

var json = JSON.stringify(obj);
console.log(json);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Your terminology is confused. JSON is a text-based, human readable, security-neutral data interchange format. Your first snippet is JSON.

If you want to turn that first snippet into an something that JavaScript can use, then...

var products = JSON.parse(data);
/* 'products' = an array of Objects */

If you want to turn 'products' back into JSON after you've done something with it, then...

var json_string = JSON.stringify(products, null, 4);
/* 'json_string' is now a 
   JSON-compatible text version 
   of 'products' with indentation 
   of 4-spaces */

See: JSON @ MDN and www.json.org

Brian Peacock
  • 1,801
  • 16
  • 24