I want to get multiple elements of each line from the JSON array one line at a time.

Asked 2 years ago, Updated 2 years ago, 88 views

JSONs include:

{
  "firstName": "John",
  "lastName": "doe",
  "age":26,
  "address": {
    "streetAddress": "naist street",
    "city": "Nara",
    "postalCode": "630-0192"
  },
  "phoneNumber": [
    {
      "type": "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type": "home",
      "number": "0123-4567-8910"
    }
  ]
}

What do you want to do

As a result of the following, is there any JSONPath that outputs the values of multiple items in each element of the array one line at a time?

[
  iPhone, 0123-4567-8888
  home, 0123-4567-88910
]

Tried

I used JSONPath, but the result was one line per item, and I didn't get the expected result.

·Tried JSONPath

$.phoneNumber[*].[type, number]

·Results

[
  "iPhone",
  "0123-4567-8888",
  "home",
  "0123-4567-8910"
]

I think it is necessary to describe repeated processing of array elements in JSON, but I do not know how to do so.
I would appreciate it if someone could let me know.Thank you for your cooperation.

json

2022-09-30 19:53

2 Answers

How about this?

 // data.
data = {
  "firstName": "John",
  "lastName": "doe",
  "age":26,
  "address": {
    "streetAddress": "naist street",
    "city": "Nara",
    "postalCode": "630-0192"
  },
  "phoneNumber": [
    {
      "type": "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type": "home",
      "number": "0123-4567-8910"
    }
  ]
}

// From data, select only phoneNumber.
source=data.phoneNumber;

// Loop each element.
for (var value of source) {
    // You can retrieve it with value.type value.number .
    // In one loop, the iPhone and its number.One more time, here's the next data.
    document.write("<span>"+value.type+"</span>:<span>"+value.number+"</span>br/>");
}


2022-09-30 19:53

Thank you for your reply.

This time it will run on JavaScript on the script engine called from Java.

Therefore, libraries for jq and other JSONPath are no longer available.

Also, there is an implementation requirement that only one string can be passed as JSONPath, and it does not support loop statements.

For each element of the array, I would like to have a method of describing JSONPath by acquiring multiple items in one line (as described in what I want to do).

I think it is probably impossible without some kind of loop or processing of the result of the acquisition, but if possible, please let me know if there is a description method that can be obtained in one line/shot.


2022-09-30 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.