Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract JSON from text

An AJAX call is returning a response text that includes a JSON string. I need to:

  1. extract the JSON string
  2. modify it
  3. then reinsert it to update the original string

I am not too worried about steps 2 and 3, but I can't figure out how to do step 1. I was thinking about using a regular expression, but I don't know how as my JSON might have multiple levels with nested objects or arrays.

like image 734
Christophe Avatar asked May 13 '12 19:05

Christophe


People also ask

How do I extract value from JSON?

To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.

How extract JSON data in Excel?

In Newer Version of ExcelSelect Data > Get Data > From File > From JSON. The Import Data dialog box appears. Search the JSON file, and then select Open.

What is JSON parsing?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.


1 Answers

For others who are looking (as I was) for extracting JSON strings from text in general (even if they're not valid), you could take a look at this Gulp plugin https://www.npmjs.com/package/gulp-extract-json-like. It searches for all strings which appear to be formatted like JSON strings.

Create a folder and install packages.

mkdir project && cd project
npm install gulp gulp-extract-json-like

Create a file ./gulpfile.js and put following content into it:

var gulp = require('gulp');
var extractJsonLike = require('gulp-extract-json-like');

gulp.task('default', function () {
  return gulp.src('file.txt')
    .pipe(extractJsonLike())
    .pipe(gulp.dest('dist'));
});

Create a file called ./file.txt which contains your text and run the following command.

gulp

Found JSON strings will be in the ./dist/file.txt.

like image 120
saamo Avatar answered Sep 17 '22 19:09

saamo