How to parse this string in json or array format in PHP?

This is a return from the Google Adwords API

Details: [fieldPath: id; trigger: Invalid predicate name: id; errorString: SelectorError.INVALID_PREDICATE_FIELD_NAME]

I would like to parse it on json / array as follows:

"Details": {
 "fieldPath": "id", 
 "trigger": "Invalid predicate", 
 "name": "id", 
 "errorString": "SelectorError.INVALID_PREDICATE_FIELD_NAME"
}
+4
source share
2 answers

You can convert the string to a collapsible format with str_replace . Then parse_str into an array. It does not guarantee operation for all returned rows, but answers your question.

<?php
$str = 'Details: [fieldPath: id; trigger: Invalid predicate name: id; errorString: SelectorError.INVALID_PREDICATE_FIELD_NAME]';

// strip out details and []
$str = str_replace(['[',']', 'Details:'], '', $str);

// fix name and replace seperators
$str = str_replace([': ', ';', ' name='], ['=', '&', '&name='], $str);

// parse string into $array variable
parse_str($str, $array);

$json = ['Details' => $array];

print_r(json_encode($json, JSON_PRETTY_PRINT));

https://3v4l.org/nKa6b

Result:

{
    "Details": {
        "fieldPath": "id",
        "trigger": "Invalid predicate",
        "name": "id",
        "errorString": "SelectorError.INVALID_PREDICATE_FIELD_NAME"
    }
}
+1
source

I think you need to create a parser for these message formats. This is a bit of a hacky solution, but you can convert this format to json and then json_decode. general idea:

  • - , (regex: ([[]. * []]) $)
  • ";" ","
  • json_decode ()

(google's) api, json

+2

Source: https://habr.com/ru/post/1692028/


All Articles