0

I want to extract all JSON objects from a string randomly containing them and add them to an array.

Sample string:

"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`

how can i extract the JSON objects from this sample string?

TeraTon
  • 435
  • 6
  • 15
FadiY
  • 119
  • 2
  • 10

2 Answers2

0

One approach to this is to use the str.search(regexp) function to find all parts of it that fulfill the JSON regex found here. So you could write a function that searches over the string for regexp matches.

To actually extract the object from the string you could use these two functions for the regex and then loop over the string until all objects have been found.

var match      = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex  = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){

  //extract the wanted part.
  jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));

  //remove the already found json part from the string and continue
  str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());

  //parse the JSON object and add it to an array.
  JSONobjects.push(JSON.parse(jsonObject));
}
Community
  • 1
  • 1
TeraTon
  • 435
  • 6
  • 15
  • Seems this should work. I will try it and get back to you later on how it went. – FadiY Apr 16 '15 at 12:52
  • Im working on the specifics, but this currently just returns the starting index of the json object, what you need is to then work out how long the object is extract it. One solution could be to combine the first and last index of regex searches here: http://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr – TeraTon Apr 16 '15 at 12:54
  • http://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr this is also usefull. – TeraTon Apr 16 '15 at 12:59
  • actually you could do both the extracting and removal with splice. – TeraTon Apr 16 '15 at 13:09
-3
var a = JSON.parse('{"name":"John"}');

a ==> Object {name: "John"}

var b = [];
b.push(a);
  • 1
    Sorry I meant to say that there will be other content than "John" and other names than "name". – FadiY Apr 16 '15 at 12:23
  • @FadiY can you add a sample string in your question that you want to parse? – Zee Apr 16 '15 at 12:26
  • @FadiY I dont understand what you are looking for? For the example string you gave the above code will work. –  Apr 16 '15 at 12:26
  • 1
    The "==>" doesn't seem to work for me. Are you sure it shouldn't be "=="? – FadiY Apr 16 '15 at 12:37
  • 1
    @FadiY That is an example of how the output of variable a will be. It is not javascript code. –  Apr 16 '15 at 13:20
  • Lol... Lol... two more chara- – 1984 Apr 17 '20 at 16:51