Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • json file

    I am trying to import a file to Stata but can't get it work. I have the and the file is:
    snd0007-1-1.0-json-ld.json
    Help on how to do this would be appreciated

  • #2
    Also I have the jsonio package

    Comment


    • #3
      https://www.statalist.org/forums/for...updated-on-ssc

      Comment


      • #4
        I tried to enter:

        jsonio kv, file(p:\snd0007-1-1.0-json-ld.json) nourl
        but received:

        java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invo ke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invo ke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl. invoke(Unknown Source)
        at java.base/java.lang.reflect.Method.invoke(Unknown Source)
        at com.stata.Javacall.load(Javacall.java:130)
        at com.stata.Javacall.load(Javacall.java:90)
        Caused by: java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
        at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknow n Source)
        at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIn dex(Unknown Source)
        at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source)
        at java.base/java.util.Objects.checkIndex(Unknown Source)
        at java.base/java.util.ArrayList.get(Unknown Source)
        at org.paces.Stata.Input.FlatJSON.flatten(FlatJSON.ja va:205)
        at org.paces.Stata.Input.FlatJSON.flatten(FlatJSON.ja va:194)
        at org.paces.Stata.Input.FlatJSON.flatten(FlatJSON.ja va:116)
        at org.paces.Stata.Input.InJSON.insheetFile(InJSON.ja va:144)
        ... 6 more
        r(5100);

        what did I do wrong?


        Comment


        • #5
          Dear Euslaner
          The error appears to occur inside jsonio while it is flattening the JSON structure:

          Caused by: java.lang.IndexOutOfBoundsException:
          Index 3 out of bounds for length 3
          at org.paces.Stata.Input.FlatJSON.flatten(FlatJSON.ja va:205)

          This does not necessarily mean that you entered the command incorrectly. However, since the original JSON file has not been shared, I cannot reproduce the error or identify which part of its structure triggers it.

          I would put the file path in quotation marks:

          jsonio kv, file("p:/snd0007-1-1.0-json-ld.json") nourl

          That is good practice, although it may not resolve this particular Java exception.

          If you have Stata 16 or later with Python configured, one workaround is to use Python's built-in JSON parser, write the contents as key–value pairs to a CSV file, and then import that file into Stata:

          python:
          import json
          import csv
          from pathlib import Path

          src = Path("p:/snd0007-1-1.0-json-ld.json")
          dst = src.with_name(src.stem + "_kv.csv")

          with src.open(encoding="utf-8-sig") as f:
          obj = json.load(f)

          def flatten(x, path=""):
          if isinstance(x, dict) and x:
          for k, v in x.items():
          k = k.replace("~", "~0").replace("/", "~1")
          yield from flatten(v, path + "/" + k)
          elif isinstance(x, list) and x:
          for i, v in enumerate(x):
          yield from flatten(v, path + "/" + str(i))
          else:
          yield path, json.dumps(x, ensure_ascii=False)

          with dst.open("w", newline="", encoding="utf-8") as f:
          writer = csv.writer(f)
          writer.writerow(["key", "value"])
          writer.writerows(flatten(obj))

          print(dst)
          end

          import delimited using ///
          "p:/snd0007-1-1.0-json-ld_kv.csv", ///
          varnames(1) stringcols(_all) encoding("utf-8") clear

          This produces one row per terminal value, with its JSON path in key and its JSON representation in value. Further restructuring may be needed to obtain the dataset you want. I have not tested this code against your file.

          Also, the filename suggests JSON-LD, which may contain metadata describing a dataset rather than the observations themselves. Could you share the file, a public download link, or a small representative example that produces the same error? That would allow a more specific diagnosis.

          Comment


          • #6
            I also encountered error report in #4, and I update jsonio, and it runs. However, Professor Choonjoo Lee's Python code maybe a more general solution.
            Code:
            . which jsonio
            c:\ado\plus\j\jsonio.ado
            *! jsonio
            *! 22FEB2018
            *! v 0.0.8

            Comment


            • #7
              I don't know whether Stata require or not, however, in Python environment, you should ensure indented block:

              Code:
              # json_to_kv_csv.py
              import csv
              import json
              from pathlib import Path
              
              src = Path("p:/snd0007-1-1.0-json-ld.json")
              dst = src.with_name(src.stem + "_kv.csv")
              
              with src.open(encoding="utf-8-sig") as f:
                  obj = json.load(f)
              
              def flatten(x, path=""):
                  if isinstance(x, dict) and x:
                      for k, v in x.items():
                          k = str(k).replace("~", "~0").replace("/", "~1")
                          yield from flatten(v, path + "/" + k)
                  elif isinstance(x, list) and x:
                      for i, v in enumerate(x):
                          yield from flatten(v, path + "/" + str(i))
                  else:
                      yield path, json.dumps(x, ensure_ascii=False)
              
              with dst.open("w", newline="", encoding="utf-8-sig") as f:
                  writer = csv.writer(f)
                  writer.writerow(["key", "value"])
                  writer.writerows(flatten(obj))
              
              print(dst)

              Comment


              • #8
                Thank you, Chen, for checking this and correcting the formatting. You are right: indentation is required inside Stata’s Python blocks as well. My code in #5 was posted without the necessary indentation; it should have been enclosed in CODE tags to preserve it.

                Thank you also for reporting that updating jsonio worked in your test. Euslaner, I would suggest trying that first. The Python approach remains an alternative for inspecting the file as key–value pairs; further restructuring may be needed for analysis.

                Comment

                Working...
                X